Skip to content Skip to sidebar Skip to footer

Generate A Json File With Python

I'm trying to generate a JSON file with python. But I can't figure out how to append each object correctly and write all of them at once to JSON file. Could you please help me solv

Solution 1:

  1. Make sure you have a valid python dictionary (it seems like you already does)

  2. I see you are trying to write your json in a file with

withopen('data.json', 'a') as f:
    f.write(json.dumps(data, ensure_ascii=False, indent=4))

You are opening data.json on "a" (append) mode, so you are adding your json to the end of the file, that will result on a bad json data.json contains any data already. Do this instead:

with open('data.json', 'w') as f:
        # wheredatais your valid python dictionary
        json.dump(data, f)

Solution 2:

Just use normal dictionaries in python when constructing the JSON then use the JSON package to export to JSON files.

You can construct them like this (long way):

a_dict = {}
a_dict['id'] = {}
a_dict['id']['a'] = {'properties' : {}}
a_dict['id']['a']['properties']['x'] = '9'
a_dict['id']['a']['properties']['y'] = '3'
a_dict['id']['a']['properties']['z'] = '17'
a_dict['id']['b'] = {'properties' : {}}
a_dict['id']['b']['properties']['x'] = '3'
a_dict['id']['b']['properties']['y'] = '2'
a_dict['id']['b']['properties']['z'] = '1'

or you can use a function:

defdict_construct(id, x, y, z):
 new_dic = {id : {'properties': {} } }
 values = [{'x': x}, {'y': y}, {'z':z}]
 for val in values:
    new_dic[id]['properties'].update(val)
 return new_dic

return_values = [('a', '9', '3', '17'), ('b', '3', '2', '1')]

a_dict = {'id': {} }
for xx in return_values:
    add_dict = dict_construct(*xx)
    a_dict['id'].update(add_dict)

print(a_dict)

both give you as a dictionary:

{'id': {'a': {'properties': {'x': '9', 'y': '3', 'z': '17'}}, 'b': {'properties': {'x': '3', 'y': '2', 'z': '1'}}}}

using json.dump:

withopen('data.json', 'w') as outfile:
    json.dump(a_dict, outfile)

you get as a file:

{
  "id": {
    "a": {
      "properties": {
        "x": "9",
        "y": "3",
        "z": "17"
      }
    },
    "b": {
      "properties": {
        "x": "3",
        "y": "2",
        "z": "1"
      }
    }
  }
}

Solution 3:

One way will be to create whole dict at once:

data = {} 
for i in range(1, 5):
    name = getname(i)
    x = getx(i)
    y = gety(i)
    z = getz(i)
    data[name] = {
        "x": x,
        "y": y,
        "z": z
      }

And then save

 with open('data.json', 'w') as f:
    json.dump(data, f, indent=4)

Post a Comment for "Generate A Json File With Python"