Reputation: 35
I have a JSON file of a list of dictionaries that I am trying to extract one particular key and its value from each dictionary and write them to a file back into JSON format.
In my code currently, I am looping through the dictionaries and appending them together in a json file. I am manually creating the json format but the key-values are written as a string. I suspect it has something to do with my dump(s) function. But is there a more efficient way to directly convert my key-values from python dictionaries to json dictionaries?
Here is my current output:
{
"text: red" #returns a string
},
{
"text: yellow"
},
{
"text: blue"
}
This is my expected output:
{
"text": "red" #returns json formatted key-value pair
},
{
"text": "yellow"
},
{
"text": "blue"
}
My current 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', 'a') as f: #append each pair
f.write("{\n") . #write key pair objects as json formatted stream to json file
json.dump("{}: {}".format(key,value), f) #format key-values
f.write("\n},\n")
My current list of dictionaries as "text.json":
{
"data": [
{
"text": "red",
"created_time": "2017-12-05",
"comment_count": 31,
"like_count": 43,
"id": "10155952999xxxxx"
},
{
"text": "yellow",
"created_time": "2017-09-09",
"comment_count": 4,
"like_count": 876,
"id": "10155952999xxxxxx"
},
{
"text": "blue",
"created_time": "2017-05-01",
"comment_count": 15,
"like_count": 6,
"id": "10155952999xxxxxx"
}
]
}
Upvotes: 0
Views: 2379
Reputation: 27
I am a novice when it comes to JSON, so I could be totally wrong...
But could a simple change in how quotations are implemented solve this issue with your current code?
json.dump('"{}": "{}"'.format(key,value), f)
Any feedback would be appreciated. I am learning too.
Upvotes: 0
Reputation: 36608
You are overthinking the solution. You can shorten it to a simple list comprehesion:
with open(join(dirname(__file__),'text.json')) as tone_json:
j = json.load(tone_json)
out = [{'text': d.get('text', 'none')} for d in j.get('data', [])]
with open('comments.json', 'a') as f:
json.dump(out, f, indent=2)
Upvotes: 2