my json file is in dictionary format, I want to read it into my Python. This is my original file.
fruit.json:
{
"Q":"Is it red?",
"yes":{
"answer":"apple"
},
"no":{
"Q":"Is it yellow",
"yes":{
"answer":"banana"
},
"no":{
"Q":"Is it sweet?",
"yes":{
"answer":"mango"
},
"no":{
"Q":"Bigger than strawberry?",
"yes":{
"answer":"lemon"
},
"no":{
"answer":"blueberry"
}
}
}
}
}
After reading them, I want to know if it's possible to print them in the same format too.
Code:
import json
import sys
s = json.loads(open(r'C:\Users\makiyo\fruit.json').read())
print(s)
print(type(s))
print("--------")
print(json.dumps(s, indent=4), file=sys.stderr)
Type of s is dict:
{'Q': 'Is it red?', 'no': {'Q': 'Is it yellow', 'no': {'Q': 'Is it sweet?', 'no': {'Q': 'Bigger than strawberry?', 'no': {'answer': 'blueberry'}, 'yes': {'answer': 'lemon'}}, 'yes': {'answer': 'mango'}}, 'yes': {'answer': 'banana'}}, 'yes': {'answer': 'apple'}}
Output:
{
"Q": "Is it red?",
"no": {
"Q": "Is it yellow",
"no": {
"Q": "Is it sweet?",
"no": {
"Q": "Bigger than strawberry?",
"no": {
"answer": "blueberry"
},
"yes": {
"answer": "lemon"
}
},
"yes": {
"answer": "mango"
}
},
"yes": {
"answer": "banana"
}
},
"yes": {
"answer": "apple"
}
}
This is not the format from the fruit.json, I don't know why they change the 'yes'/'no' location like this.