سؤال

I've read the simplejson docs and don't understand why it sometimes returns a json object with single quotes (which php can't understand) and other times returns an escaped sequence of double quotes (also not recognized in php). I could probably do regex on the output string as a bandaid, but I'd rather understand the source of the problem.

Example:

INPUT: (The starting data in python)

print stories

{'text': 'HIV/AIDS One day, \r\nThen we took her home and we called for the meeting and told the villagers that we should take care of her and give her the good care that she need in her lifetime before she depart.', 'id': 1215L}

And as a sanity check - the json object looks normal before cherrypy gets a hold of it:

print simplejson.dumps( stories )

[{"text": "youth to youth empowerment... yada yada yada...", "id": 12828}, {"text": "women ... yada yada yada...", "id": 12828}]

...
import simplejson
return simplejson.dumps( stories )

[some obscure magic happens with cherrypy...] Here's the part in cherrypy that passes the json to a browser:

@cherrypy.expose
def browse_stories(self):
    stories = test_org_match.browse_org_story_matches()
    cherrypy.response.headers['Content-Type'] = 'application/json'
    return json.dumps( stories )

Output (what I see in a browser calling this object via cherrypy):

"[{\"text\": \"POVERTY We decided to steal the vegetables. There was nothing we could do. We had stayed for two days without food and these third day we could not keep up. We had to eat something or we would die. We started slowly towards the shamba and took as much as we could we went home and cooked and ate and we felt better.\", \"id\": 33109}, {\"text\": \"Boda Bado They simply on transport basis people can move round using bada-boda transport to save time \r\n It relay helped the rural people deep in the village to transport themeselves to the other ears using motorcycle bicycle. \", \"id\": 35931}]"

(The enclosed text is different but this happens with any one of the random text snippets it is pulling)

NOTE: I believe the other case where simplejson returns an object with single quotes everywhere is because I passed str(dictionary) instead of the actual dictionary. Of course, php breaks when you serve up single-quoted json. But the "free" escaping baffles me - and is happening inside cherrypy I think.

هل كانت مفيدة؟

المحلول

I figured it out. My code uses json.dumps() and then it uses json.dumps again - so the extra escape characters is json treating this as a string and not as a dictionary object.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top