Python not parsing JSON correctly all the time.

2019-06-08 18:59发布

Getting this back from a JSON object:

The call is made here:

response = make_request(GET_QUALIFIED_OFFERS_URL, request)

def make_request(url, json_data):
    host = url
    req = urllib2.Request(host, json_data, {'content-type': 'application/json'})
    response_stream = urllib2.urlopen(req)

    return response_stream.read()

response = {"Violations":[],"Messages":[],"Log":[],"Session":{"SessionId":813982132},"W3iDeviceId":294294043,"IsAfppOfferwallEnabled":true}, skipkeys=True, ensure_ascii=False, sort_keys=True, indent=4}

print json.dumps((response), sort_keys=True, indent=4)

Getting an error:

print json.dumps({"Violations":[],"Messages":[],"Log":[],"Session":{"SessionId":813982132},"W3iDeviceId":294294043,"IsAfppOfferwallEnabled":true}, skipkeys=True, ensure_ascii=False, sort_keys=True, indent=4)
NameError: global name 'true' is not defined

It looks like some of the JSON isn't correct. I put quotes around the value "true" and it works. So is there any way to put quotes around all the values?

This Works:

response = {"Violations":[],"Messages":[],"Log":[],"Session":{"SessionId":813982132},"W3iDeviceId":294294043,"IsAfppOfferwallEnabled":"true"}, skipkeys=True, ensure_ascii=False, sort_keys=True, indent=4}

The problem is I have JSON like this all over the place with values like false and true with no quotes in huge key--value data sets.

What I am trying to do is take the JSon and make it pretty to be able to compare against it. I am trying to write an automation frame work to test what comes back in the Json. Ideally I would love to create like a csv ouput. Maybe have a column for each key and then have a row for each value. Anyone else doing something like this?

2条回答
Anthone
2楼-- · 2019-06-08 19:18

There's difference between writing pure JSON-string and converting a Python data structure into JSON-string.

Python's JSON{En,De}coder performs following translations by default:

JSON            Python

object          dict
array           list
string          unicode
number (int)    int, long
number (real)   float
true            True
false           False
null            None

So when you write {'foo': True} in Python, JSONEncoder writes out {'foo': true} as per JSON-standard.

查看更多
我命由我不由天
3楼-- · 2019-06-08 19:25

In Python the keyword is True, not true. Case sensitivity counts. By way of example usage for both dumps and loads:

>>> from json import dumps, loads
>>>
>>> d1 = {'key1': 'val1', 'key2': True, 'key3': False}
>>> s1 = dumps(d1)
>>> d2 = loads(s1)
>>> d1
{'key3': False, 'key2': True, 'key1': 'val1'}
>>> s1
'{"key3": false, "key2": true, "key1": "val1"}'
>>> d2
{u'key3': False, u'key2': True, u'key1': u'val1'}
查看更多
登录 后发表回答