0

I have the JSON variable var with the following content:

[{"name":"name0", "surname":"surname01", "surname2":"surname02", "number": 0}, {"name":"name1", "surname":"surname11", "surname2":"surname12", "number": 1}]

And I want to write in a JSON file just the name and the number fields.
Currently, I am doing it the following way:

f.write('[')
for a, i in enumerate(var):
  f.write('{"name":' + i['name'] + ', "number":' + i['number'] + '}')
  if(a==0):
    f.write(',')
f.write(']')
f.close()

Is there a better way to write to a file a subset of the JSON fields in Python?

khelwood
  • 52,115
  • 13
  • 74
  • 94
Alvaro Gomez
  • 330
  • 2
  • 5
  • 21
  • 2
    Three changes. 1) Use json library. 2) Use with statement. 3) Consider whether you need to wrap it in an array. [This answer](http://stackoverflow.com/a/12309296/1175496) describes the `json` library. – The Red Pea Mar 29 '16 at 12:11
  • 1
    I would make a python list/dictionary and `json.dump` that instead of manually writing text to a file – OneCricketeer Mar 29 '16 at 12:11

2 Answers2

2

You could use a list comprehension and the json module to make this shorter;

import json
json.dump([{'name': i['name'], 'number': i['number']} for i in var ], f) 
jmetz
  • 11,167
  • 3
  • 28
  • 40
1

You could use the json module and convert it to al list

import json
newVar = []
for i in var:
    newVar.append({'name': i['name'], 'number': i['number']})
return json.dumps(newVar)

however this is not much better, just different

Hans
  • 1,971
  • 3
  • 20
  • 34