I am attempting to:
- Load data from a JSON list of dictionaries
- Write the values of a specific key from each dictionary to a file
Yet, when I attempt to dump the key pairs to the new .json file, it only prints the very last dictionary key pair. Anyone know how to loop through each dictionary and append the key pair? I have tried a few methods but I can't seem to figure out what i'm missing and where.
Here is my code:
with open(join(dirname(__file__),'text.json')) as tone_json:
python_obj = json.load(tone_json) #read file object into string
my_list = python_obj["data"] #assign list name to string
for dictionary in my_list: #loop through dictionaries in list
for key,value in dictionary.items(): #loop through key pairs in dictionaries
if key == "text":
with open('comments.json', 'w') as f:
json.dump("{}: {}".format(key,value), f) #write key pair objects as json formatted stream to json file
f.write('\n')
A sample of my JSON file:
{
"data": [
{
"text": "apple",
"created_time": "2017-12-23",
"comment_count": 154,
"like_count": 856,
"id": "1015595299xxxxx"
},
{
"text": "orange",
"created_time": "2017-12-04",
"comment_count": 13,
"like_count": 437,
"id": "10155952xxxxx"
},
{
"text": "grapes",
"created_time": "2017-12-04",
"comment_count": 12,
"like_count": 163,
"id": "1015595299xxxxx"
}
]
}
My current output:
"text: grapes"
But, I want to loop through every dictionary and eventually print only the values from each "text" key.
Expected Output:
"text: apple"
"text: orange"
"text: grapes"
Any hints will help! Thanks!
json.dump()when you're practically not writing a JSON? Why not justf.write("{}: {}\n".format(key, value))instead? Also, open the file inamode to prevent overwriting of the entries from your previous runs.json.write(...)butf.write(...). Also, while your input file is a JSON file, the data you're attempting to write in the output file most certainly isn't.