简体   繁体   中英

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 solve this? a, b, and values for x, y, z are calculated in the script. Thank you so much

This is how the generated JSON file should look like

 {
  "a": {
    "x": 2,
    "y": 3,
    "z": 4
  },
  "b": {
    "x": 5,
    "y": 4,
    "z": 4
  }
}

This is python script

import json    
for i in range(1, 5):
    a = geta(i)
    x = getx(i)
    y = gety(i)
    z = getz(i)
    data = {
      a: {
        "x": x,
        "y": y,
        "z": z
      }}


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

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:

def dict_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:

with open('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"
      }
    }
  }
}
  1. Make sure you have a valid python dictionary (it seems like you already do)

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

with open('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:
        # where data is your valid python dictionary
        json.dump(data, f)
        

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)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM