3

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
3
  • 2
    because this is not json. data=... is invalid syntax Commented May 20, 2015 at 13:33
  • 2
    it is not json format.. Commented May 20, 2015 at 13:34
  • this is the data am getting on a post request . And the data is comming in this format only , and am taking it as request.body. thats why its creating a issue. Commented May 20, 2015 at 13:39

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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"}}'

3 Comments

This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient reputation you will be able to comment on any post.
My understanding on the question was why he was getting a ValueError once he was trying to load the string. I consider it a valid answer that gives an indication to search for a solution that can go either way: implement a valid response if he has control over it or try to find an alternative solution and post a specific question if that fails.
This does answer the question. The reason the OP cannot JSON decode the response is because it's not valid JSON.
0
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

1 Comment

the a is like this -- a = ' [ data = { ' ' : ' ' } ] '

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.