nilay gupta
nilay gupta

Reputation: 195

converting json string to dict in python

I am getting a value in request.body, it is like :

a = '[data={"vehicle":"rti","action_time":"2015-04-21 14:18"}]'

type(a) == str

I want to convert this str to dict. i have tried by doing this

b=json.loads(a)

But am getting error

ValueError: No JSON object could be decoded

Upvotes: 3

Views: 2297

Answers (3)

Narcisse Doudieu Siewe
Narcisse Doudieu Siewe

Reputation: 649

import json

a = '[data={"vehicle":"rti","action_time":"2015-04-21 14:18"}]'
r = a.split("=")
r[:] = r[0].replace("[", ""), r[1].replace("]", "") 
d = '{"%s":%s}'%(r[0],r[1])
dp = json.loads(d)  
print dp

Upvotes: 0

Bryan Oakley
Bryan Oakley

Reputation: 385870

The data you are receiving is not properly formatted JSON. You're going to have to do some parsing or data transformation before you can convert it using the json module.

If you know that the data always begins with the literal string '[data=' and always ends with the literal string ']', and that the rest of the data is valid json, you can simply strip off the problematic characters:

b = json.loads(a[6:-1])

If the data can't be guaranteed to be in precisely that format, you'll have to learn what the actual format is, and do more intelligent parsing.

Upvotes: 2

chaos
chaos

Reputation: 490

It is not a valid json format that you are receiving. A valid format is of type:

'{"data":{"vehicle":"rti","action_time":"2015-04-21 14:18"}}'

Upvotes: 0

Related Questions