class - json

最後更新: 2015-05-22

JSON(JavaScript Object Notation)

 

 


要 import 的 class:

import json

Encoding:Python -> Json

json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])
'["foo", {"bar": ["baz", null, 1.0, 2]}]'

Decoding:Json -> Python

# Load a json string

json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
[u'foo', {u'bar': [u'baz', None, 1.0, 2]}]

# Load a file object

jdata = json.load(fo)

json 與 python 的 type 對應

JSON          Python
object        dict
array         list
string        unicode
number (int)  int, long
number (real) float
true          True
false         False
null          None

Pretty printing:

import json
print json.dumps({'4': 5, '6': 7}, sort_keys=True,
    indent=4, separators=(',', ': '))

Output

{
    "4": 5,
    "6": 7
}

# JSON be represented using either UTF-8, UTF-16, or UTF-32, with UTF-8 being the default.

Since the default item separator is ','

You can use separators=(',', ': ') to avoid this.

 

Creative Commons license icon Creative Commons license icon