2016-12-20 7 views
-1

Ich habe Requests-Modul verwendet und jetzt habe ich die Daten zurück im JSON-Format und durch die Hilfe von How to Python prettyprint a JSON file habe ich meinen Code geschrieben und während der Ausführung des Codes gab es mir einen Fehler , also habe ich die an den Parser übergebene Variable in string geändert. Jetzt gab es wieder einen Fehler.Fehler beim Parsen der JSON und Formatierung zu hübschen JSON

#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)) 

Fehlerprotokoll:

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) 

Jede Lösung für dieses Problem?

Antwort

5

ValueError: Expecting property name: line 1 column 2 (char 1)

Das Problem ist, str(got_data_in_json) ist kein gültiger 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''}" 

Die got_data_in_json ist bereits eine Struktur Python Daten, die Sie Dump können:

got_data_in_json = r.json() 
print(json.dumps(got_data_in_json, indent=4, sort_keys=True)) 
+0

Dank es funktionierte. –

1

r.json() parst die JSON für Sie und gibt eine Python-Datenstruktur zurück. Es ist nicht erforderlich, json.loads() für diese Daten aufzurufen.

1

r.json() kehrt JSon

so brauchen Sie nicht json.loads(str(got_data_in_json))

import requests 
import json 

r = requests.post('http://httpbin.org/post', data = {'key':'value'}) 
print(r.status_code) 
got_data_in_json = r.json() 
print(json.dumps(got_data_in_json, indent=4 ,sort_keys=True)) 

Ausgang:

200 
{ 
    "args": {}, 
    "data": "", 
    "files": {}, 
    "form": { 
     "key": "value" 
    }, 
    "headers": { 
     "Accept": "*/*", 
     "Accept-Encoding": "gzip, deflate", 
     "Content-Length": "9", 
     "Content-Type": "application/x-www-form-urlencoded", 
     "Host": "httpbin.org", 
     "User-Agent": "python-requests/2.11.1" 
    }, 
    "json": null, 
    "origin": "103.227.98.245", 
    "url": "http://httpbin.org/post" 
}