我从mysql DB中获取了许多json字符串,应该将它们组合起来。
例如:
{
"type": "device",
"name": "Lampe",
"controls": [
{
"type": "switch",
"name": "Betrieb",
"topic": "/lampe/schalter"
}
]
}
组合这些设备应该进入一个json文件数组
{
"name": "Test-System",
"devices": [
{
"type": "device",
"name": "Lampe",
"controls": [
{
"type": "switch",
"name": "Betrieb",
"topic": "/lampe/schalter"
}
]
},
{
other Device
}
]
}
我不明白如何在python中执行此操作
有人知道该怎么做吗?
答案 0 :(得分:3)
可以使用json
模块。
#!/usr/bin/env python3.5
import json
# Parse each device JSON file.
device1 = json.load(open("device-switch-Lampe.json"))
device2 = json.load(open("device-sensor-Wert.json"))
# more devices ...
obj = {"name": "Test-System", "devices": [device1, device2]}
print(json.dumps(obj))
输出(美化):
{
"devices": [{
"type": "device",
"controls": [{
"type": "switch",
"topic": "/lampe/schalter",
"name": "Betrieb"
}],
"name": "Lampe"
}, {
"type": "device",
"controls": [{
"type": "sensor",
"topic": "/sensor/wert",
"name": "Wert"
}],
"name": "Sensor"
}],
"name": "Test-System"
}
答案 1 :(得分:2)
有两种方法可以做到这一点 - 通过处理字符串或使用Python-JSON数据结构。前者就像是
# untested code
s = '''{
"name": "Test-System",
"devices": [ '''
while True:
j = get_json_from_DB()
if not j: break # null string or None
s = s + j + ',\n'
s = s[:-2] + ']\n}\n' #[:-2 loses the last ',\n' from the loop
或者,如果您想使用Python loaded-JSON,那么
import json
# untested code
s = {
"name": "Test-System",
"devices": []
}
while True:
j = get_json_from_DB()
if not j: break # null string or None
s['devices'].append( json.loads(j) )
# str = json.dumps(s) # ought to be valid
后者将验证所有传入的json字符串(json.loads()
将为任何错误的JSON抛出异常),并且对于大量设备将更有效。因此,除非您在具有少量器件的RAM约束嵌入式系统中工作,否则它将成为首选,其中后者的更大内存占用是一个问题。