【问题标题】:How to append data to JSON list that doesn't contains any key for that list?如何将数据附加到不包含该列表任何键的 JSON 列表?
【发布时间】:2020-11-27 19:03:35
【问题描述】:
[
  {
   "name": "name one",
   "id": 1
  },
  {
   "name": "name two",
   "id": 2
  }
]

我想将对象附加到 .json 文件中的列表中。我该怎么办?

【问题讨论】:

  • 你可以分享一些代码吗?当你坐在对象时,你能分享你想附加的吗?
  • 嗨,您的示例不是 JSON,而是它的对象数组。如果您希望它是 JSON 格式,则必须使用 {} 和一个密钥进行包装。
  • @NirGofman,在我看来是完全有效的 JSON。
  • @NirGofman 在我看来像 JSON,可以被 json.loads 解析。
  • @RitikSwami,如果您只是读取该文件的内容,然后添加您要添加​​的内容,最后将其写回该文件,该怎么办?

标签: python json list file


【解决方案1】:

您可以读取现有的 json 内容更新它并重写更新的列表。

import json

with open("myfile.json", "r+") as f:
    my_file = f.read()  # read the current content
    my_list = json.loads(my_file)  # convert from json object to dictionary type
    dict_obj = {
        "name": "name three",
        "id": 3
    }
    my_list.append(dict_obj)
    f.seek(0)  # sets  point at the beginning of the file
    f.truncate()  # Clear previous content
    print(f" going to rewrite {my_list}")
    f.write(json.dumps(my_list))  # Write updated version file

【讨论】:

  • 谢谢你。这对我们来说意义重大。
  • 很高兴它对您有所帮助。
【解决方案2】:

我不完全确定您在问什么,但也许下面的代码会有所帮助:

const myList = [
  {
   "name": "name one",
   "id": 1
  },
  {
   "name": "name two",
   "id": 2
  }
]

const myNewItem = {
   "name": "name three",
   "id": 3
  }

const addItemIfDifferentId = (list, newItem) => [...list, !list.map(({id}) =>id).includes(newItem.id) ? {...newItem} : {} ]

const newList = addItemIfDifferentId(myList, myNewItem)

newList

【讨论】:

  • 感谢您的回复斯科特。但这不是我要找的答案。
【解决方案3】:

也许这会对你有所帮助:

import json 
   
# When loading a .json files it will be a string:
with open('data.json') as json_file:
    x = json.load(json_file) //{"key1":"123",  "key2":"456",  "key3":"789"}

    # python object to be appended 
    y = {"key4": "101112"} 
  
    # Load the json string to be an object type:
    z = json.loads(x) 
   
    # appending the data 
    z.update(y) 
  
    # the result is a JSON string: 
    print(json.dumps(z))  

    with open('data.json', 'w') as outfile:
        json.dump(z, outfile)

【讨论】:

  • 赞赏,但我如何将它附加到 .JSON 文件中而不分配任何变量。这是一个 JSON 文件,兄弟。
  • TypeError: JSON 对象必须是 str、bytes 或 bytearray,而不是 list。
  • 顺便说一句,谢谢您的回复。我得到了我的答案。赞赏你的努力。谢谢 Nir ​​Gofman。
猜你喜欢
  • 2020-09-05
  • 1970-01-01
  • 2022-01-17
  • 2021-10-24
  • 2016-08-14
  • 2022-12-06
  • 2015-10-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多