0

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?

0

2 Answers 2

4

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) 
Sign up to request clarification or add additional context in comments.

Comments

0

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.