【问题标题】:Modify JSON data representation in Python在 Python 中修改 JSON 数据表示
【发布时间】:2017-07-20 07:57:51
【问题描述】:

假设我有这本字典

{'person': {'field1': 'text1', 'field2': 'text2'}}

json.dumps 是否可以像这样序列化它

{'person[field1]': 'text1', 'person[field2]': 'text2'}

我知道我可以自己做,但我想问是否有内置方法,因为在 javascript 中有。

【问题讨论】:

  • 循环遍历每个人,将新的key person[field1]添加到新的json对象中,并删除旧json中的旧key
  • 如果json.dumps 有内置的方法,我会感到非常惊讶,因为它不是标准的序列化方法。
  • "{'person[field1]': 'text1', 'person[field2]': 'text2'}" 不是有效的 json。

标签: python json object nested


【解决方案1】:

json 无法做到这一点。你必须自己做:

new_data = {
    f'{d}[{k}]' : v for k, v in json_data[d].items() for d in json_data
}
new_data
# {'person[field1]': 'text1', 'person[field2]': 'text2'}

【讨论】:

    猜你喜欢
    • 2019-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多