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

Categories

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

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

1 Answer

  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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...