Search code examples
pythonjsonrecords

How to write a large number of nested records in JSON with Python


I want to produce a JSON file, containing some initial parameters and then records of data like this:

{
 "measurement" : 15000,
 "imi" : 0.5,
 "times" : 30,
 "recalibrate" : false,
 {
  "colorlist" : [234, 431, 134]
  "speclist" : [0.34, 0.42, 0.45, 0.34, 0.78]
 }
 {
  "colorlist" : [214, 451, 114]
  "speclist" : [0.44, 0.32, 0.45, 0.37, 0.53]
 }
 ...
}

How can this be achieved using the Python json module? The data records cannot be added by hand as there are very many.

EDIT: Solved with help from @Aprillion. Here is the resulting code as in the program:

data=[]
i=0
while i<measurement:
  data.append({"colorlist" : listcolorlist[i], "speclist" : listspeclist[i]})
  i+=1
python_data = {
  "measurement" : measurement,
  "imi" : imi,
  "times" : times,
  "recalibrate" : recalibrate,
  "data": data
}
print(json.dumps(python_data, indent=4))

Solution

  • a) you use invalid json format in your question
    b) exept False vs. false python data formats will be exactly the same as JSON in this example

    UPDATE: code based on updated question (using list comprehension instead of while loop):

    import json
    measurement = 2
    listcolorlist = [[234, 431, 134],
                     [214, 451, 114]]
    listspeclist = [[0.34, 0.42, 0.45, 0.34, 0.78],
                    [0.44, 0.32, 0.45, 0.37, 0.53]]
    python_data = {"measurement" : 15000,
                   "imi" : 0.5,
                   "times" : 30,
                   "recalibrate" : False,
                   "data" : [{"colorlist" : listcolorlist[i],
                              "speclist" : listspeclist[i]}
                             for i in range(measurement)]}
    print(json.dumps(python_data))