Python dict 通过 json.loads 转换为 JSON:

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4571684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 16:22:54  来源:igfitidea点击:

Python dict to JSON via json.loads:

pythondjangojsonhttp-post

提问by Nick Ruiz

I have troubleshooting some code that uses HTTP POST to send data and should return a JSON result whose contents are a dictionary. I am using an XML-RPC wrapper to expose this service. When the wrapper receives the dict information from the http response variable, the dict contents are in a string in this form:

我对一些使用 HTTP POST 发送数据的代码进行了故障排除,并应返回内容为字典的 JSON 结果。我正在使用 XML-RPC 包装器来公开此服务。当包装器从 http 响应变量中接收到 dict 信息时,dict 内容以这种形式出现在一个字符串中:

{'created': datetime.datetime(2010, 12, 31, 19, 13, 8, 379909), 'worker': u'GoogleWorker', 'ready': False, 'request_id': '8f1381853a444a42a37ae5152a3af947', 'owner': u'admin', 'shortname': u'test19'}

I'm trying to convert the string below into a JSON result using the following statement:

我正在尝试使用以下语句将下面的字符串转换为 JSON 结果:

result = json.loads(response[1])

However, when I try to use json.loads to convert the data to JSON, I get the following error: Fault: <Fault 1: "<type 'exceptions.ValueError'>:Expecting property name: line 1 column 1 (char 1)">

但是,当我尝试使用 json.loads 将数据转换为 JSON 时,出现以下错误: Fault: <Fault 1: "<type 'exceptions.ValueError'>:Expecting property name: line 1 column 1 (char 1)">

I manually tried to convert the above string to JSON, but I get the same error. Is the dict malformed in some way? Is it due to unicode? I also tried setting the locale to UTF-8, but that was unsuccessful.

我手动尝试将上述字符串转换为 JSON,但出现相同的错误。dict 是否以某种方式格式错误?是因为unicode吗?我还尝试将语言环境设置为 UTF-8,但没有成功。

Any help would be greatly appreciated.

任何帮助将不胜感激。

采纳答案by Daniel Roseman

You are trying to use the wrong method. json.loadsis for loading JSON to Python. If you want to convert Python to JSON, you need json.dumps.

您正在尝试使用错误的方法。json.loads用于将 JSON 加载到 Python。如果要将 Python 转换为 JSON,则需要json.dumps.

result = json.dumps(response[1])

回答by Spike Gronim

That dict is in Python dict literal format, not JSON. You can do:

该 dict 是 Python dict 文字格式,而不是 JSON。你可以做:

import ast
result = ast.literal_eval(response[1])

to read in the response in that format. Are you sure that Django hasn't already JSON-decoded the response?

以该格式读取响应。您确定 Django 尚未对响应进行 JSON 解码吗?

回答by Jorge Machado

i have use json on django , i use this :

我在 django 上使用了 json,我使用了这个:

import simplejson as json
#to encode
final= {'first':first_data,'second':second_data}
json.dumps(final)
#to decode this is the example from python's api 
json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')