0

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!

Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55
MillieJA
  • 31
  • 1
  • 7
  • 1
    You can open another file and just start writing in it. https://stackoverflow.com/questions/19508703/how-to-open-a-file-through-python I would open it before for loop and close it after for loop. – Yoshikage Kira Jun 20 '21 at 08:46
  • 1
    Also, this will be helpful [Read from file and write to another python](https://stackoverflow.com/questions/50435295/read-from-file-and-write-to-another-python/50435495) See the method with 19 votes. It is using the with keyword which is preferable in my opinion. – Yoshikage Kira Jun 20 '21 at 08:49
  • @Goion Thanks so much man, both of those look like exactly what I need for accessing the file – MillieJA Jun 20 '21 at 08:54

2 Answers2

1

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))
norie
  • 9,609
  • 2
  • 11
  • 18
1

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

Barbaros Özhan
  • 59,113
  • 10
  • 31
  • 55