2009-06-24 92 views
9

迴應我的other question現在需要找到一種方法將json壓縮到一行:用python鍛鍊json

{"node0":{ 
    "node1":{ 
     "attr0":"foo", 
     "attr1":"foo bar", 
     "attr2":"value with  long  spaces" 
    } 
}} 

想下來緊縮一行:

{"node0":{"node1":{"attr0":"foo","attr1":"foo bar","attr2":"value with  long  spaces"}}} 

通過移除無關緊要的空間和保存是值之內的人。有沒有一個庫在Python中做到這一點?

編輯 謝謝drdaeman和Eli Courtwright的超快反應!

+1

您正在使用的Python版本在這裏有些相關。自從我認爲json已經成爲標準庫的一部分2.6 – Triptych 2009-06-24 17:56:34

+0

使用python 2.6,所以建議的解決方案對我很有幫助 – 2009-06-24 19:36:23

回答

16

http://docs.python.org/library/json.html

>>> import json 
>>> json.dumps(json.loads(""" 
... {"node0":{ 
...  "node1":{ 
...   "attr0":"foo", 
...   "attr1":"foo bar", 
...   "attr2":"value with  long  spaces" 
...  } 
... }} 
... """)) 
'{"node0": {"node1": {"attr2": "value with  long  spaces", "attr0": "foo", "attr1": "foo bar"}}}' 
+3

哦,我差點忘了它...你應該使用'(',',': ')`作爲json.dumps的`separators`參數(參見文檔)。這將使數據更加緊湊。 – drdaeman 2009-06-24 17:57:37

1

在Python 2.6:

import json 
print json.loads(json_string) 

基本上,當你使用JSON模塊來解析JSON,那麼你得到Python字典。如果你只是打印字典和/或將其轉換爲字符串,它將全部在一行上。當然,在某些情況下,Python的字典會比JSON編碼字符串(如用布爾和空值)略有不同,因此,如果這則重要的,你可以說

import json 
print json.dumps(json.loads(json_string)) 

如果你沒有的Python 2.6那麼你可以使用the simplejson module。在這種情況下,您只需說

import simplejson 
print simplejson.loads(json_string)