create json object in python code example
Example 1: print json python
import json
uglyjson = '{"firstnam":"James","surname":"Bond","mobile":["007-700-007","001-007-007-0007"]}'
parsed = json.loads(uglyjson)
print(json.dumps(parsed, indent=2, sort_keys=True))
Example 2: python json string to object
import json
x = '{ "name":"John", "age":30, "city":"New York"}'
y = json.loads(x)
print(y["age"])
Example 3: how to create json file in python
import json
dictionary ={
"name" : "sathiyajith",
"rollno" : 56,
"cgpa" : 8.6,
"phonenumber" : "9976770500"
}
with open("sample.json", "w") as outfile:
json.dump(dictionary, outfile)
Example 4: list to json python
import json
friends_list = [
'John','Rambo','Sam',
]
json_format = json.dumps(friends_list)
print(json_format)
print(type(json_format))
["John", "Rambo", "Sam"]
<class 'str'>
Example 5: Json in python
import json
json_file = json.load(open("your file.json", "r", encoding="utf-8"))
print(json_file)
Example 6: python to json
x = {
"name": "John",
"age": 30,
"city": "New York"
}
y = json.dumps(x)