简体   繁体   中英

How to parse this json in Python

I am using a module that outputs data in this format:

j = ("{u'auth_user': {u'first_name': u'a', u'last_name': u'b', u'uid': u'x', u'timezone_offset': u'7200', u'timezone': u'Europe', u'mail': u'x'}, u'server_time': 1390844912, u'table': {u'rows': [{u'c': [{u'v': u'20140126'}, {u'v': u'-35.9'}]}, {u'c': [{u'v': u'20140115'}, {u'v': u'-37.02'}]}, {u'c': [{u'v': u'20131222'}, {u'v': u'-48.1'}]}, {u'c': [{u'v': u'20131213'}, {u'v': u'-53.28'}]}, {u'c': [{u'v': u'20131209'}, {u'v': u'-26.8'}]}, {u'c': [{u'v': u'20131203'}, {u'v': u'-12.36'}]}], u'cols': [{u'type': u'date', u'label': u'date'}, {u'type': u'number', u'label': u'amount'}]}}")

I want to extract the negative value from this data.

I think it is json but I guess maybe it is not valid.

I can't parse it.

json.loads(j)

This returns:

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

How can I deal with parsing this data? How can I extract the negative values from it?

It is not valid JSON. If someone sends it to you claiming it's JSON, you can go and hit them with a stick.

It is a valid python dict literal, though, so you could use:

import ast
ast.literal_eval(j) 

as wim said you can extract them by using ast.literal_eval as it is valid python literal

import ast
l = ast.literal_eval(j)

the second part is interesting after pretty printing your json to see the pattern

import pprint
pprint.pprint(l)
{u'auth_user': {u'first_name': u'a',
                u'last_name': u'b',
                u'mail': u'x',
                u'timezone': u'Europe',
                u'timezone_offset': u'7200',
                u'uid': u'x'},
 u'server_time': 1390844912,
 u'table': {u'cols': [{u'label': u'date', u'type': u'date'},
                      {u'label': u'amount', u'type': u'number'}],
            u'rows': [{u'c': [{u'v': u'20140126'}, {u'v': u'-35.9'}]},
                      {u'c': [{u'v': u'20140115'}, {u'v': u'-37.02'}]},
                      {u'c': [{u'v': u'20131222'}, {u'v': u'-48.1'}]},
                      {u'c': [{u'v': u'20131213'}, {u'v': u'-53.28'}]},
                      {u'c': [{u'v': u'20131209'}, {u'v': u'-26.8'}]},
                      {u'c': [{u'v': u'20131203'}, {u'v': u'-12.36'}]}]}}

the negative values are all at the same place so can be extracted doing this

print([cell[u'c'][1][u'v'] for cell in l[u'table'][u'rows']])
[u'-35.9', u'-37.02', u'-48.1', u'-53.28', u'-26.8', u'-12.36']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM