Working With JSON Data in Python
How to parse Nested Json Data in Python? How to read and write Json Data in File
If you are working with Json, include the json module in your code.
import json
Convert Python Objects to Json string in Python. And then from Json string to Json Dictionary.
import json
# a Python object (dict):
x = {
"name": "John",
"age": 30,
"city": "New York"
}
# convert into JSON string:
y = json.dumps(x)
# convert json string to Json Dict
jsonDict = json.loads(y)
Now to access any Json key.
import json
x = {
"name": "John",
"age": 30,
"city": "New York"
}
# convert into JSON string:
y = json.dumps(x)
# convert json string to Json Dict
jsonDict = json.loads(y)
print (jsonDict['name'])
print (jsonDict['age'])
Write the json data in the file
import json
data = {
'bill': 'tech',
'federer': 'tennis',
'ronaldo': 'football',
'people' : [ {
'name': 'Scott',
'website': 'stackabuse.com',
'from': 'Nebraska'},
{'name': 'Larry',
'website': 'google.com',
'from': 'Michigan' } ]
}
with open('data.txt', 'w') as outfile:
json.dump(data, outfile)
Read the data from Json file (We will read the same data file in which we dump the data above)
import json
with open('data.txt') as json_file:
data = json.load(json_file)
print ("bill:", data['bill'])
print ("")
for person in data['people']:
print("Name:", person['name'])
print("Website:", person['website'])
print("From:", person['from'])
print("")
Iterate through Json data which has list, json string, nested Json. Here I will explain how to work with complex Json and extract data from it
import json
def checkList(ele, prefix):
for i in range(len(ele)):
if (isinstance(ele[i], list)):
checkList(ele[i], prefix+"["+str(i)+"]")
elif (isinstance(ele[i], str)):
printField(ele[i], prefix+"["+str(i)+"]")
else:
checkDict(ele[i], prefix+"["+str(i)+"]")
def checkDict(jsonObject, prefix):
for ele in jsonObject:
if (isinstance(jsonObject[ele], dict)):
checkDict(jsonObject[ele], prefix+"."+ele)
elif (isinstance(jsonObject[ele], list)):
checkList(jsonObject[ele], prefix+"."+ele)
elif (isinstance(jsonObject[ele], str)):
printField(jsonObject[ele], prefix+"."+ele)
def printField(ele, prefix):
print (prefix, ":" , ele)
data = {'field1': 'hello1',
'field2': 'hello2',
'NestedJson': {'Field': 'helloNested1',
'List': [{'f01': 'v01', 'f02': 'v02'},
{'f11': 'v11'}],
'NestedNestedJson': {'Field1': 'value1',
'Field2': 'value2'}
},
'List': [{'a1': 'b1'},
{'a1': 'b1'}],
'ElementList': ['ele1', 'ele2', 'ele3']
}
#Iterating all the fields of the JSON
for element in data:
#If Json Field value is a Nested Json
if (isinstance(data[element], dict)):
checkDict(data[element], element)
#If Json Field value is a list
elif (isinstance(data[element], list)):
checkList(data[element], element)
#If Json Field value is a string
elif (isinstance(data[element], str)):
printField(data[element], element)
The Output of above code is:-
field1 : hello1
field2 : hello2
NestedJson.Field : helloNested1
NestedJson.List[0].f01 : v01
NestedJson.List[0].f02 : v02
NestedJson.List[1].f11 : v11
NestedJson.NestedNestedJson.Field1 : value1
NestedJson.NestedNestedJson.Field2 : value2
List[0].a1 : b1
List[1].a1 : b1
ElementList[0] : ele1
ElementList[1] : ele2
ElementList[2] : ele3
what if a null value for any of the fields? it prompts error. Thanks
it’s not possible to initiate json with null value. If it’s empty string than it will process it.
Thanks… It was a good post…
Hi Simran,
This code looks so neat, thank you for sharing!
I’ve been trying to do the reverse process, but I failed a couple of times. Do you have any tips on how I should go about converting your output back to JSON?
I really like this whole idea with paths and was so eager to use it. But initializing the structure based on this turned out to be a huge endeavor.
Thanks,
Ana
Hi Ana,
Thanks! I’ll write a block on this soon. If you need any help feel free to reach out to me.