json tutorial python code example
Example 1: python json string to object
import json
x = '{ "name":"John", "age":30, "city":"New York"}'
y = json.loads(x)
print(y["age"])
Example 2: python json stringify
import json
json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'
print(json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True))
{"a": 0, "b": 0, "c": 0}
Example 3: Json in python
import json
json_file = json.load(open("your file.json", "r", encoding="utf-8"))
print(json_file)
Example 4: python to json
x = {
"name": "John",
"age": 30,
"city": "New York"
}
y = json.dumps(x)
Example 5: python import json data
import ast
def import_json(filename):
for line in open(filename):
yield ast.literal_eval(line)
data = list(import_json("/path/to/filename.json"))
dataframe = pd.DataFrame.from_dict(data)
Example 6: json.loads
>>> import json
>>> json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
['foo', {'bar': ['baz', None, 1.0, 2]}]
>>> json.loads('"\\"foo\\bar"')
'"foo\x08ar'
>>> from io import StringIO
>>> io = StringIO('["streaming API"]')
>>> json.load(io)
['streaming API']