【问题标题】:update json list from a list从列表中更新 json 列表
【发布时间】:2021-05-05 14:22:32
【问题描述】:

如何更新json列表/数组?

j = '''[{"title": "AIG Index", "country": "AUD"}, {"title": "NFP Payrol", "country": "USD"}]'''
    ff = json.loads(j)
add = {"info":"ok"}
print(ff)

[{'title': 'AIG Index', 'country': 'AUD'}, {'title': 'NFP Payrol', 'country': 'USD'}]

for i in (ff):
  i.update(add)
print(ff)

[{'title': 'AIG Index', 'country': 'AUD', 'info': 'ok'}, {'title': 'NFP Payrol', 'country': 'USD', '信息':'好的'}]

如果我想根据数组更新怎么办? 使用 zip / enumerate 不适用于 json

add = [{"info":"ok"}, {"info":"not ok"}]

我得到错误, ValueError:字典更新序列元素#0 的长度为1; 2 是必需的, 如何获得结果

[{'title': 'AIG Index', 'country': 'AUD', 'info': 'ok'}, {'title': 'NFP Payrol', 'country ': 'USD', 'info': '不行'}]

【问题讨论】:

    标签: python json


    【解决方案1】:

    我认为 python dicts 没有内置 zip。 但你可以简单地使用这样的东西:

    >>> add = [{"info":"ok"}, {"info":"not ok"}]
    >>> for count,i in enumerate(ff):
    ...     i.update(add[count])
    ... 
    >>> ff
    [{'title': 'AIG Index', 'country': 'AUD', 'info': 'ok'}, {'title': 'NFP Payrol', 'country': 'USD', 'info': 'not ok'}]
    >>> 
    

    【讨论】:

      【解决方案2】:

      我认为这是你想要做的:

      import json
      
      ff = json.loads(
          '''[{"title": "AIG Index", "country": "AUD"}, {"title": "NFP Payrol", "country": "USD"}]''')
      
      add = [{"info": "ok"}, {"info": "not ok"}]
      
      for i, f in enumerate(ff):
          f.update(add[i])
      

      或者您可以使用列表推导:

      ff = [dict(f, **a) for f, a in zip(ff, add)]
      

      【讨论】:

      • 像魅力一样工作?。非常感谢?
      【解决方案3】:

      由于你的数据看起来很简单,你可以使用pandas打开你的数据,做任何你需要的操作,然后使用to_json()函数再次保存。

      这是一个例子

      import pandas as pd
      j = '''[{"title": "AIG Index", "country": "AUD"}, {"title": "NFP Payrol",  "country": "USD"}]'''
      df1 = pd.read_json(j)
      df1['ok'] = ['ok','not ok']
      df1.to_json('file.json')
      

      【讨论】:

      • 我添加了我在 pandas 中的操作方式,仅供参考。
      猜你喜欢
      • 1970-01-01
      • 2015-09-28
      • 2022-01-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多