再向JSON文件添加一个属性

时间:2018-06-18 01:20:46

标签: python json random

所以我有一个生成的JSON,其中一个看起来像(有很多只有唯一ID)

# load library
require(data.table)

# convert data.frame to data.table
setDT(df2)

# create an id column (it will be later removed)
df2[, id := 1:.N]

# Estimate and assign the minimum (output 1 of optimize) 
#      for each flow and leng values:
df2[, minimum := optimize(hazwil2, 
                          interval = c(0.1, 12), 
                          flow, 
                          leng)[[1]], 
       by = id]

# Estimate and assing objective (output 2 of optimize)
#             for each pair of flow and leng:
df2[, objective := optimize(hazwil2, 
                            interval = c(0.1, 12), 
                            flow, 
                            leng)[[2]], 
      by = id]

# remove id column
df2[, id := NULL]

# view df2:
> df2
     leng flow diam  minimum    objective
  1:  100   10    2 11.99994 1.902594e-05
  2:  200   10    2 11.99994 3.805188e-05
  3:  300   10    2 11.99994 5.707782e-05
  4:  400   10    2 11.99994 7.610376e-05
  5:  500   10    2 11.99994 9.512970e-05
 ---                                     
196:  600  200    2 11.99994 2.930926e-02
197:  700  200    2 11.99994 3.419414e-02
198:  800  200    2 11.99994 3.907902e-02
199:  900  200    2 11.99994 4.396390e-02
200: 1000  200    2 11.99994 4.884877e-02

我试图做"追加"一个新字段,但我收到错误

{
    "id": 1,
    "name": "name",
    "dep": "dep",
    "Title": "Title',
    "email": "email"
}

有一些方法可以再添加一个" key:value"生成之后呢?

3 个答案:

答案 0 :(得分:1)

有两个问题:

  1. 您正在使用json.dump生成列表,但您并未使用json.load重新创建Python数据结构。
  2. 您在第二次打开调用中以w模式打开文件,这会截断它
  3. 尝试将每个步骤分解为自己的步骤并分离变异数据并写入磁盘。

    with open('data.json', 'w') as file:
        json.dump(write_list, file)
    #file.close()                     # manually closing files is unnecessary, 
                                      # when using context managers
    
    with open('data.json', 'r') as json_file:
        write_list = json.load(json_file)
        entry = {'parentId': random.randrange(0, 487, 2)}
        write_list.append(entry)
    
    with open('data.json', 'w') as json_file:
        json.dump(write_list, file)
    

答案 1 :(得分:0)

执行所需操作的步骤为文件:

  1. 将整个JSON文件解析为python词典。
  2. 将条目添加到字典中。
  3. 将字符串序列化为JSON。
  4. 将JSON文件写回文件。

答案 2 :(得分:0)

在我使用Tim McNamara的建议完成此功能之后,我发现了一种更好的方法来为文件中的每个JSON dict添加新行

for randomID in write_list:
    randomID['parentId'] = random.randrange(0, 487, 2)

with open('data.json', 'w') as file:
    json.dump(write_list, file)