我如何克服在python中组合两个json文件时我结束的额外'\'?

moo*_*oon 0 python json

我试图结合两个json文件,但在我的输出结束时有一些奇怪的"\".

import json

data1 = {'apple': 'good',"mango": "excellent"}

json_data1 = json.dumps(data1)

data2 = {'mustang': 'good',"camaro": "excellent"}

json_data2 = json.dumps(data2)

final_data = { 'fruit' : str(json_data1), 'car' : str(json_data2) }

json_final = json.dumps(final_data)

print(json_final)
Run Code Online (Sandbox Code Playgroud)

期望:

{"fruit": "{"apple": "good", "mango": "excellent"}", "car": "{"camaro": "excellent", "mustang": "good"}"}
Run Code Online (Sandbox Code Playgroud)

我得到了什么:

{"fruit": "{\"apple\": \"good\", \"mango\": \"excellent\"}", "car": "{\"camaro\": \"excellent\", \"mustang\": \"good\"}"}
Run Code Online (Sandbox Code Playgroud)

我该如何克服这个问题?

另外,在我的实际问题中,我只得到两个JSON对象,而我无法控制其他任何东西.

Cha*_*ffy 5

如果您的数据是本机Python结构

根本不要单独对包含的内容进行字符串化或JSON编码.将您的内容保持为纯粹的本机数据结构,并仅编码为JSON 一次.

否则,当您运行第一个json.dumps()传递时,您将生成一个字符串 - 当您调用json.dumps()包含该字符串的数据结构时,您将生成一个编码该字符串的JSON序列,而不是一个编码原始字符串的JSON数据结构创建字符串以表示的字典.

import json

data1 = {'apple': 'good',"mango": "excellent"}
data2 = {'mustang': 'good', "camaro": "excellent"}
final_data = { 'fruit' : data1, 'car' : data2 }
json_final = json.dumps(final_data)
Run Code Online (Sandbox Code Playgroud)

如果您的输入已经是JSON编码的......

安全的方法是在重新编码之前解码为本机结构.那是:

json_data1 = '{"mango": "excellent", "apple": "good"}'
json_data2 = '{"camaro": "excellent", "mustang": "good"}'
final_data = { 'fruit': json.loads(json_data1), 'car': json.loads(json_data2) }
json_final = json.dumps(final_data)
Run Code Online (Sandbox Code Playgroud)

不安全的方法是使用字符串连接:

# DANGER: Will produce badly-formed output instead of throwing an exception if input is bad
json_data1 = '{"mango": "excellent", "apple": "good"}'
json_data2 = '{"camaro": "excellent", "mustang": "good"}'
json_final = '{ "fruit": %s, "car": %s }' % (json_data1, json_data2)
Run Code Online (Sandbox Code Playgroud)