[PYTHON] [Introduction to json] No, I was addicted to it. .. .. ♬

This time, I was dealing with a json file that was traversed by AWS Lambda, and I had a lot of trouble, so I will organize the json code a little.

** json is really great ♬ **

No commentary is included. If you read the flow while collating it with the result, you will understand the meaning.

import json

s = r'{"C": "\u3042", "\u3044": {"i": "\u3046", "j": 2}, "B": [{"X": 1, "Y": 10}, {"X": 2, "Y": 20}]}'

print("******************")
print(type(s))
print("s=",s)
print(s[5:20])

print("*****'String'.encode('Character code name')*************")
b = s.encode('cp932')
print(type(b))
print("b=",b)
print(b[5:20])

print("*****b'Byte sequence'.decode('Character code name')*************")
c = b.decode('cp932')
print(type(c))
print("c=",c)
print(c[5:20])

print("*****json.loads(s)*************")
dict = json.loads(s)
print(type(dict))
print("dict=",dict)
print(dict["C"])

print("*****json.dumps(dict)*************")
enc = json.dumps(dict)
print(type(enc))
print("enc=",enc)
print(enc[5:20])

print("*****json.loads(enc)*************")
dict2 = json.loads(enc)
print(type(dict2))
print("dict2=",dict2)
print(dict2["I"])

print("*****json.dumps(dict2)*************")
enc = json.dumps(dict2)
print(type(enc))
print("enc=",enc)
print(enc[5:20])

print("*****b.decode("utf-8")*************")
db = b.decode("utf-8")
print(type(db))
print("db=",db)
print(db[5:20])

print("*****k.encode('utf-8')*************")
k = r'{"C": "\u3042", "\u3044": "Hello!"}'
ke =k.encode('utf-8')
print("ke=",ke)
jke =json.loads(ke)
print(jke)
print("jke['C']=",jke['C'])
print("jke['I']=",jke['I'])

print("*****json.dumps(dict, default=expireEncoda)*************")
from datetime import datetime
def expireEncoda(object):
    if isinstance(object, datetime):
        return object.isoformat()
dict = {"now": datetime.now()}
enc = json.dumps(dict, default=expireEncoda)
print("dict=",dict)
print("dict['now']=",dict['now'])
print("enc=",enc)

denc =json.loads(enc)
print("denc['now']=",denc['now'])

Output result

The output of the above code is as follows.

>python ex_jason.py
******************
<class 'str'>
s= {"C": "\u3042", "\u3044": {"i": "\u3046", "j": 2}, "B": [{"X": 1, "Y": 10}, {"X": 2, "Y": 20}]}
 "\u3042", "\u3
*****'String'.encode('Character code name')*************
<class 'bytes'>
b= b'{"C": "\\u3042", "\\u3044": {"i": "\\u3046", "j": 2}, "B": [{"X": 1, "Y": 10}, {"X": 2, "Y": 20}]}'
b' "\\u3042", "\\u3'
*****b'Byte sequence'.decode('Character code name')*************
<class 'str'>
c= {"C": "\u3042", "\u3044": {"i": "\u3046", "j": 2}, "B": [{"X": 1, "Y": 10}, {"X": 2, "Y": 20}]}
 "\u3042", "\u3
*****json.loads(s)*************
<class 'dict'>
dict= {'C': 'Ah', 'I': {'i': 'U', 'j': 2}, 'B': [{'X': 1, 'Y': 10}, {'X': 2, 'Y': 20}]}
Ah
*****json.dumps(dict)*************
<class 'str'>
enc= {"C": "\u3042", "\u3044": {"i": "\u3046", "j": 2}, "B": [{"X": 1, "Y": 10}, {"X": 2, "Y": 20}]}
 "\u3042", "\u3
*****json.loads(enc)*************
<class 'dict'>
dict2= {'C': 'Ah', 'I': {'i': 'U', 'j': 2}, 'B': [{'X': 1, 'Y': 10}, {'X': 2, 'Y': 20}]}
{'i': 'U', 'j': 2}
*****json.dumps(dict2)*************
<class 'str'>
enc= {"C": "\u3042", "\u3044": {"i": "\u3046", "j": 2}, "B": [{"X": 1, "Y": 10}, {"X": 2, "Y": 20}]}
 "\u3042", "\u3
*****b.decode("utf-8")*************
<class 'str'>
db= {"C": "\u3042", "\u3044": {"i": "\u3046", "j": 2}, "B": [{"X": 1, "Y": 10}, {"X": 2, "Y": 20}]}
 "\u3042", "\u3
*****k.encode('utf-8')*************
ke= b'{"C": "\\u3042", "\\u3044": "\xe3\x81\x93\xe3\x82\x93\xe3\x81\xab\xe3\x81\xa1\xe3\x81\xaf\xef\xbc\x81"}'
{'C': 'Ah', 'I': 'Hello!'}
jke['C']=Ah
jke['I']=Hello!
*****json.dumps(dict, default=expireEncoda)*************
dict= {'now': datetime.datetime(2020, 6, 22, 21, 13, 57, 761568)}
dict['now']= 2020-06-22 21:13:57.761568
enc= {"now": "2020-06-22T21:13:57.761568"}
denc['now']= 2020-06-22T21:13:57.761568

【reference】 ① Let's master json dumps with Python! (encoding, foramt, datetime)How to convert character code with Python [For beginners]Reading / writing JSON files / strings with Python

Summary

-Json file can be extracted by specifying it with dictionary type,'heading character': ・ How to identify json files;

<class 'dict'>
{'name': 'tarou', 'age': 23, 'gender': 'man'}
<class 'str'>
{"name": "tarou", "age": 23, "gender": "man"}

** ・ json.loads (converted from str to dict) is different from json.load (read JSON file as a dictionary) ** ** ・ json.dumps (convert from dict to str; can be converted to a character string) is different from json.dump (save dictionary as JSON file) ** ・ Others. .. ..

Recommended Posts

[Introduction to json] No, I was addicted to it. .. .. ♬
I was addicted to multiprocessing + psycopg2
[IOS] GIF animation with Pythonista3. I was addicted to it.
I was addicted to pip install mysqlclient
I was addicted to Flask on dotCloud
What I was addicted to Python autorun
Use Python from Java with Jython. I was also addicted to it.
Docker x visualization didn't work and I was addicted to it, so I summarized it!
I set up TensowFlow and was addicted to it, so make a note
I was addicted to scraping with Selenium (+ Python) in 2020
AttributeError: I was addicted to'module' object has no attribute'MyTestCase'
A story that I was addicted to at np.where
I was able to repeat it in Python: lambda
I was addicted to trying logging.getLogger in Flask 1.1.x
What I was addicted to when using Python tornado
Introduction to Nonlinear Optimization (I)
What I was addicted to when migrating Processing users to Python
PyTorch's book was difficult to understand, so I supplemented it
[Fixed] I was addicted to alphanumeric judgment of Python strings
When I tried to install PIL and matplotlib in a virtualenv environment, I was addicted to it.
[Introduction to Python] How to parse JSON
A story that I was addicted to calling Lambda from AWS Lambda.
The record I was addicted to when putting MeCab on Heroku
What I was addicted to when introducing ALE to Vim for Python
What I was addicted to with json.dumps in Python base64 encoding
A note I was addicted to when making a beep on Linux
Note that I was addicted to sklearn's missing value interpolation (Imputer)
A note I was addicted to when creating a table with SQLAlchemy
I was addicted to confusing class variables and instance variables in Python
Two things I was addicted to building Django + Apache + Nginx on Windows
I want to tweet on Twitter with Python, but I'm addicted to it
When I tried to run Python, it was skipped to the Microsoft Store
I was addicted to running tensorflow on GPU with NVIDIA driver 440 + CUDA 10.2
A story I was addicted to when inserting from Python to a PostgreSQL table
A story I was addicted to trying to install LightFM on Amazon Linux
I was addicted to creating a Python venv environment with VS Code
A story I was addicted to trying to get a video url with tweepy
[Introduction to Pytorch] I played with sinGAN ♬
I was addicted to not being able to use Markdown on pypi's long_description
The file name was bad in Python and I was addicted to import
[Python] I was addicted to not saving internal variables of lambda expressions
I was addicted to trying Cython with PyCharm, so make a note
I thought it was the same as python, and I was addicted to the problem that the ruby interpreter did not start.
The file edited with vim was readonly but I want to save it
What I was addicted to when creating a web application in a windows environment
P100-PCIE-16GB was added to the GPU of Google Colab before I knew it
Three things I was addicted to when using Python and MySQL with Docker
AtCoder AGC 041 C --I was addicted to the full search of Domino Quality
I was able to mock AWS-Batch with python, moto, so I will leave it
Summary of points I was addicted to running Selenium on AWS Lambda (python)
A note I was addicted to when running Python with Visual Studio Code
A story that I was addicted to when I made SFTP communication with python
I was able to recurse in Python: lambda
Anyway, I want to check JSON data easily
I wrote "Introduction to Effect Verification" in Python
[Introduction to Python] How to handle JSON format data
[Introduction to PID] I tried to control and play ♬
Introduction to MQTT (Introduction)
Introduction to Scrapy (1)
I was soberly addicted to calling awscli from a Python 2.7 script registered in crontab
Introduction to Supervisor