I have a json file containing this
[
{
"results": [
{
"names": [
"Ben",
"Sam"
]
},
{
"names": [
"John",
"Max"
]
}
]
}
]
And I want to take each string from the names array for each result and append it to a txt file called names.txt, and have each string seperated by a comma. Like this
Ben, Sam, John, Max
I haven't used Python much so I'm a bit stuck with writing to another file but also on reading from the json file. I currently have
with open('results.json') as json_file:
data = json.load(json_file)
for item in data['results']:
names = item['names']
And from there is where I'm just about stuck. Appreciate any help or advice anyone can give, thanks!
There's a slight problem with your JSON, the comma after "Max"
makes it invalid.
If you fix that you can use this code to read the file, get a list of the names and write them to another file, results_names.txt
import json
with open('results.json') as json_file:
data = json.load(json_file)
names = []
for item in data[0]['results']:
names.extend(item['names'])
with open('results_names.txt', 'w') as txt_file:
txt_file.write(', '.join(names))
You can use an alternative method which combines opening and closing related files
import json
with open('results.json','r') as f_in, open('output.txt', 'w') as f_out:
data = json.load(f_in)
for i in list(range(0,len(data)+1)):
s=data[0]['results'][i]['names']
if i>0:
f_out.write(',')
f_out.write(','.join(s))
where we should be careful when putting comma between every seperate objects
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.