假设我正在处理字典中的以下两个(或更多)JSON 字符串:
JSONdict['context'] = '{"Context":"{context}","PID":"{PID}"}'
JSONdict['RDFchildren'] = '{"results":[ {"object" : "info:fedora/book:fullbook"} ,{"object" : "info:fedora/book:images"} ,{"object" :"info:fedora/book:HTML"},{"object":"info:fedora/book:altoXML"},{"object":"info:fedora/book:thumbs"},{"object":"信息:fedora/book:originals"} ]}'
我想创建一个合并的 JSON 字符串,其中“上下文”和“查询”作为根级键。像这样的东西:
{"context": {"PID": "wayne:campbellamericansalvage", "Context": "object_page"}, "RDFchildren": {"results": [{"object": "info:fedora/book:fullbook"} , {"object": "info:fedora/book:images"}, {"object": "info:fedora/book:HTML"}, {"object": "info:fedora/book:altoXML"}, { "object": "info:fedora/book:thumbs"}, {"object": "info:fedora/book:originals"}]}}
以下工作,但我想eval()
尽可能避免使用。
# using eval
JSONevaluated = {}
for each in JSONdict:
JSONevaluated[each] = eval(JSONdict[each])
JSONpackage = json.dumps(JSONevaluated)
也得到了这种工作方式,但感觉很hackish,我担心随着更现实的元数据出现,编码和转义会成为问题:
#iterate through dictionary, unpack strings and concatenate
concatList = []
for key in JSONdict:
tempstring = JSONdict[key][1:-1] #removes brackets
concatList.append(tempstring)
JSONpackage = ",".join(concatList) #comma delimits
JSONpackage = "{"+JSONpackage+"}" #adds brackets for well-formed JSON
有什么想法吗?建议?