I used to handle json data in Python, but I will introduce it because it has an affinity with the Python standard dict type.
Here It will be very helpful. Thank you very much. JavaScript Object Notation A notation for expressing data. Similar to JavaScript syntax, but treated independently of JavaScript. Functions that can handle JSON in programming languages other than JavaScript are prepared.
Since this article focuses on using JSON, detailed explanations will be omitted. The format is as follows. It feels like value is linked to key.
{
"key":value,
"key":value,
"key":value
}
The key and value set is the same as the Python dict.
There is a json module in Python. It mainly converts dict⇔json.
Use json.dumps
to convert dict to json.
The type of dict is of course dict, but after conversion it will be str type.
import json
sample_dict = {"Japan":"Tokyo","UK":"London","USA":"Washington, D.C."}
print(type(sample_dict))
print(sample_dict)
#output
# <class 'dict'>
# {'Japan': 'Tokyo', 'UK': 'London', 'USA': 'Washington, D.C.'}
#conversion
sample_json = json.dumps(sample_dict)
print(type(sample_json))
print(sample_json)
#output
# <class 'str'>
# {"Japan": "Tokyo", "UK": "London", "USA": "Washington, D.C."}
You can also convert from pandas DataFrame or pandas Series to json. Personally, I'm grateful that I use pandas a lot.
Use to_json ()
to convert pandasDataFrame (Series) to json.
import pandas as pd
df_sample = pd.DataFrame([[1,1,1],[2,3,4],[8,7,6]],columns=["x","y","z"],index=["A","B","C"])
json_df = df_sample.to_json()
print(df_sample)
print(json_df)
#output
x y z
A 1 1 1
B 2 3 4
C 8 7 6
{"x":{"A":1,"B":2,"C":8},"y":{"A":1,"B":3,"C":7},"z":{"A":1,"B":4,"C":6}}
Use json.loads to load json data. Use sample_json from earlier.
dict_json = json.loads(sample_json)
print(type(dict_json))
print(dict_json)
#output
# <class 'dict'>
# {'Japan': 'Tokyo', 'UK': 'London', 'USA': 'Washington, D.C.'}
Of course dict_json is a Python dict
print(dict_json['Japan'])
#output
# Tokyo
You can access it in this way.
Since json can be used not only in python but also in other languages, it is convenient for communication between languages. I've only explained the minimum here, but please try it!
I tried using it myself, and since I wrote it from the perspective of something like that, I thought that all the articles could not be touched on comprehensively. For the time being, I will continue to write about what I have used, and if I need to review it, I will update the article.
Recommended Posts