mark mark - 1 year ago 114
Python Question

python: How to use json.dumps on windows?

I am running python on windows and trying to pretty print a json output. Here is what I get:

>>> ta
{u'Status': {u'code': 200, u'request': u'geocode'}, u'Placemark': [{u'Point': {u'coordinates': [34.777821, 32.066157, 0]}, u'ExtendedData': {u'LatLonBox': {u'west': 34.71
37913, u'east': 34.8418507, u'north': 32.1039719, u'south': 32.0283265}}, u'AddressDetails': {u'Country': {u'CountryName': u'\u05d9\u05e9\u05e8\u05d0\u05dc', u'Locality':
{u'LocalityName': u'\u05ea\u05dc \u05d0\u05d1\u05d9\u05d1 \u05d9\u05e4\u05d5'}, u'CountryNameCode': u'IL'}, u'Accuracy': 4}, u'id': u'p1', u'address': u'Tel Aviv, Israel
'}], u'name': u'Tel Aviv'}
>>> json.dumps(ta, sort_keys=True, indent = 4)
'{\n "Placemark": [\n {\n "AddressDetails": {\n "Accuracy": 4, \n "Country": {\n "CountryName": "\\u
05d9\\u05e9\\u05e8\\u05d0\\u05dc", \n "CountryNameCode": "IL", \n "Locality": {\n "LocalityName": "\\u05ea\\u
05dc \\u05d0\\u05d1\\u05d9\\u05d1 \\u05d9\\u05e4\\u05d5"\n }\n }\n }, \n "ExtendedData": {\n "LatLo
nBox": {\n "east": 34.8418507, \n "north": 32.1039719, \n "south": 32.0283265, \n "west": 34.7
137913\n }\n }, \n "Point": {\n "coordinates": [\n 34.777821, \n 32.066157, \n
0\n ]\n }, \n "address": "Tel Aviv, Israel", \n "id": "p1"\n }\n ], \n "Status": {\n
"code": 200, \n "request": "geocode"\n }, \n "name": "Tel Aviv"\n}'

Why doesn't it work?

Answer Source

It did work. Remember that the JSON representation of a dictionary looks very much like Python syntax. Try printing out the return value from json.dumps and see if it looks more like you expect:

s = json.dumps(ta, sort_keys=True, indent = 4)
print s
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download