Manas Chaturvedi
Manas Chaturvedi

Reputation: 5540

ValueError: malformed string

I am working with an API which returns the following unicode as response:

    dd = u"""{"meta":{"request":{"granularity":"Weekly","main_domain_only":false,
"domain":"borivali.me",
    "country":"world"},"status":"Success",
"last_updated":"2016-05-09"},"bounce_rate":[{"date":"2016-04-12","bounce_rate":0.5},
    {"date":"2016-04-19","bounce_rate":0.13355382826388454},
{"date":"2016-04-26","bounce_rate":0.0},
    {"date":"2016-05-03","bounce_rate":0.23602940883106352}]}"""

I'm trying to parse this information in the following way:

ddd = ast.literal_eval(dd)
print ddd

However, I get the following error:

ValueError: malformed string

What seems to be wrong with my code?

PS: dd stores a unicode string and not a dictionary.

Upvotes: 0

Views: 7851

Answers (1)

Łukasz Rogalski
Łukasz Rogalski

Reputation: 23203

Assuming following definition is correct:

s = u"""{"meta":{"request":{"granularity":"Weekly","main_domain_only":false,
"domain":"borivali.me",
    "country":"world"},"status":"Success",
"last_updated":"2016-05-09"},"bounce_rate":[{"date":"2016-04-12","bounce_rate":0.5},
    {"date":"2016-04-19","bounce_rate":0.13355382826388454},
{"date":"2016-04-26","bounce_rate":0.0},
    {"date":"2016-05-03","bounce_rate":0.23602940883106352}]}"""

Given that declaration, s is JSON document and may be parsed to Python objects with json library.

import json
p = json.loads(s)

ast module is used to deserialise repr of Python objects, and repr does not equal JSON serialization in general case. Following relations holds (at least for simple Python types, well defined in JSON standard - lists, dicts and strings).

d == ast.literal_eval(repr(d))
d == json.loads(json.dumps(d))

Upvotes: 4

Related Questions