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!

3
  • 1
    You can open another file and just start writing in it. stackoverflow.com/questions/19508703/… I would open it before for loop and close it after for loop. Commented Jun 20, 2021 at 8:46
  • 1
    Also, this will be helpful Read from file and write to another python See the method with 19 votes. It is using the with keyword which is preferable in my opinion. Commented Jun 20, 2021 at 8:49
  • @Goion Thanks so much man, both of those look like exactly what I need for accessing the file Commented Jun 20, 2021 at 8:54

2 Answers 2

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))
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.