【问题标题】:Python to dynamically build JSON with sub arraysPython 使用子数组动态构建 JSON
【发布时间】:2016-07-20 15:02:22
【问题描述】:

我可以从简单的字典 {} 和 List [] 构建 JSON,但是当我尝试构建更复杂的结构时。我在输出 JSON 中嵌入了“\”。

我想要的结构:

{"name": "alpha",
 "results": [{"entry1": 
        [
        {"sub1": "one"}, 
        {"sub2": "two"}
        ]
    }, 
    {"entry2": 
        [
        {"sub1": "one"}, 
        {"sub2": "two"}
        ]
    }
]
}

这是我得到的:

   {'name': 'alpha',
    'results': '[{"entry1": "[{\\\\"sub1\\": \\\\"one\\\\"}, {\\\\"sub2\\\\": '
            '\\\\"two\\\\"}]"}, {"entry2": "[{\\\\"sub1\\\\": \\\\"one\\\\"}, 
    {\\\\"sub2\\\\": '
            '\\\\"two\\\\"}]"}]'}

注意嵌入的 \\.每次代码通过 json.dumps 时都会附加另一个 \。

这里的代码几乎可以工作,但不能:

import json
import pprint
testJSON = {}

testJSON["name"] = "alpha"

#build sub entry List
entry1List = []
entry2List = []
topList = []
a1 = {}
a2 = {}
a1["sub1"] = "one"
a2["sub2"] = "two"

entry1List.append(a1)
entry1List.append(a2)

entry2List.append(a1)
entry2List.append(a2)

# build sub entry JSON values for Top List
tmpDict1 = {}
tmpDict2 = {}
tmpDict1["entry1"] = json.dumps(entry1List)
tmpDict2["entry2"] = json.dumps(entry2List)
topList.append(tmpDict1)
topList.append(tmpDict2)

# Now lets' add the List with 2 sub List to the JSON
testJSON["results"] = json.dumps(topList)

pprint.pprint (testJSON)

【问题讨论】:

  • 您将编码的 JSON 嵌入到 dict 中,然后重新编码已经编码的 JSON。如果你想“合并” JSON,只需“合并”字典
  • 简单:首先以 Pyhon dict 或列表的形式构建数据,最后使用 json.dumps(data) 将其转换为 JSON。 JSON不是特殊的数据类型,它是以字符串的形式表示一些数据的序列化方法。

标签: python json dynamic


【解决方案1】:

看看这一行:

tmpDict1["entry1"] = json.dumps(entry1List)

这是指定键entry1 具有将entry1List 转换为json 的字符串输出 的值。本质上,它是将 JSON 放入 JSON 字符串中,所以它被转义了。要嵌套数据结构,我会选择:

tmpDict1["entry1"] = entry1List

其他地方也一样。一旦有列表和字典树 - 您应该只需要在根容器(字典或列表)上调用一次json.dumps()

【讨论】:

  • 啊!有道理——我的使用模式是错误的。谢谢你的澄清。我会重做我的方法。
  • 经过测试 - 效果很好。所以首先构建结构,然后使用 json.dumps() 函数。感谢您的洞察力。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-28
  • 2020-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多