假设我正在处理字典中的以下两个(或更多)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”: “info:fedora / book:originals”}]}'
我想创建一个合并的JSON字符串,其中“context”和“query”作为根级别键。像这样:
{“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”: “信息:fedora的/书:原稿”}]}}
以下有效,但我希望尽可能避免使用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
有什么想法?建议?
答案 0 :(得分:1)
您可以在第一个示例中使用json.loads()
代替eval()
。