Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python's json.load(sys.stdin) gets me u'...' instead of double quotes around Strings

When I do:

import sys, json;
import requests

headers = {'Content-Type': 'application/json',
       'X-Parse-Application-Id': '...',
       'X-Parse-REST-API-Key': '...'}

data = json.load(sys.stdin)
for station in data["data"]:
    print station
    res = requests.post('https://api.parse.com/1/classes/test4', data=station, headers=headers)

I get

{u'city': u'London',
...
}

And it's not a valid Json as when I try to POST it to Parse.com I'm getting

{"code":107,"error":"invalid JSON"}

and any JSON validator gives me Error:Strings should be wrapped in double quotes.

How to make a valid JSON of the data?

like image 262
Marian Paździoch Avatar asked Jan 04 '16 11:01

Marian Paździoch


People also ask

Does JSON have to be double quotes?

JSON names require double quotes.

How do you escape a double quote in JSON Python?

Escaping double quotes in a string replaces each double quote in the string with \" . For example, escaping double quotes in the string '123 "abc" 456' results in "123 \"abc\" 456" .

How do you escape a quote in JSON?

If you're making a . json text file/stream and importing the data from there then the main stream answer of just one backslash before the double quotes: \" is the one you're looking for.

Does JSON dump escape quotes?

Furthermore, all double quotes of the actual JSON formatting are escaped with a backslash.


2 Answers

print will just print python's representation of the object you are passing (which you deserialized with json.load). Try this:

import sys, json;
data = json.load(sys.stdin)
for station in data["data"]:
    print(json.dumps(station))

json.dumps serializes a python object back to json.

like image 175
m fran Avatar answered Sep 20 '22 15:09

m fran


You've misunderstood what json.load does: it deserializes from JSON, ie it creates Python objects from JSON strings.

But I can't really understand what you're doing; if you already have JSON being passed in from stdin, why are you trying to convert it at all? Pass it straight on to your API.

like image 26
Daniel Roseman Avatar answered Sep 21 '22 15:09

Daniel Roseman