解析json并格式化为漂亮的json时出错

Sai*_*ran 0 python json python-2.7 python-3.x python-requests

我已经使用了请求模块,现在我得到了json格式的数据,并且通过这个如何使用Python的相同帮助我写了一个JSON文件,我编写了我的代码,在执行代码时它给了我一个错误Expected a string or buffer,所以我改变了变量传递给解析器到字符串.现在它再次出现了另一个错误.

#Import
import requests
import json

r = requests.post('http://httpbin.org/post', data = {'key':'value'})
print(r.status_code)
got_data_in_json = r.json()
parsed_json = json.loads(str(got_data_in_json))
print(json.dumps(parsed_json, indent=4 ,sort_keys=True))
Run Code Online (Sandbox Code Playgroud)

错误日志:

python requests_post.py
200
Traceback (most recent call last):
  File "requests_post.py", line 8, in <module>
    parsed_json = json.loads(str(got_data_in_json))
  File "/usr/lib/python2.7/json/__init__.py", line 339, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 364, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 380, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)
Run Code Online (Sandbox Code Playgroud)

解决这个问题的任何方法?

ale*_*cxe 6

ValueError:期望属性名称:第1行第2列(char 1)

问题是,str(got_data_in_json)不是有效的JSON:

In [2]: str(got_data_in_json)
Out[2]: "{u'files': {}, u'origin': u'50.57.61.145', u'form': {u'key': u'value'}, u'url': u'http://httpbin.org/post', u'args': {}, u'headers': {u'Content-Length': u'9', u'Accept-Encoding': u'gzip, deflate', u'Accept': u'*/*', u'User-Agent': u'python-requests/2.11.1', u'Host': u'httpbin.org', u'Content-Type': u'application/x-www-form-urlencoded'}, u'json': None, u'data': u''}"
Run Code Online (Sandbox Code Playgroud)

got_data_in_json已经是一个可以转储的Python数据结构:

got_data_in_json = r.json()
print(json.dumps(got_data_in_json, indent=4, sort_keys=True))
Run Code Online (Sandbox Code Playgroud)