Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

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))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  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

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...