Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit

Working with JSON in Python

Python primer

• String: 'abc' or "abc"

•  List: x = ['abc', 25]

– x[0] =?

– x.append(True) // True is boolean

– x.append(None) // None is NoneType

• Tuple: y = ('abc', 25)

– y[0] =?

– What about y.append(True)?

Python primer

•  Dictionary: z = {'name': 'john', 25: 'age'}

– Note key in Python can also be integer or tuple

– z['name'] = ?

– z[25]=?

– What about z['age'] or z['25']?

• z['gender'] = 'male'

– z = {25: 'age', 'name': 'john', 'gender': 'male'}

Working with JSON in Python

•  import json

– Loading json library module

• json.dumps()

– JSON encoder

– Python object => JSON document

• json.loads()

– JSON decoder

– JSON document => Python object

Python object => JSON document

•  Python list => JSON array

– json.dumps([1, 2]) => '[1, 2]'

– json.dumps([3, 'abc', True, None]) => '[3, "abc", true, null]'

•  Python tuple => JSON array

– json.dumps((1, 'abc')) => '[1, "abc"]'

•  Python dictionary => JSON object

– json.dumps({'name': 'john', 25: 'age'}) => '{"25": "age", "name": "john"}'

•  Notes

None => null

True => true

'abc' => "abc"

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

– '["foo", {"bar": ["baz", null, 1.0, 2]}]'

•  json.dumps({(1,2): 5})

– Error (key is a tuple, Ok in Python)

– dumps() doesn't take tuple as key (but see below)

• json.dumps({(2): 5}) => '{"2": 5}'

JSON document => Python object

• JSON object => Python dictionary

•  json.loads('{"name": "john", "age": 5}') => {u'age': 5, u'name': u'john'}

Note: 'u' means "unicode"

•  JSON array => Python list

•   json.loads('[25, "abc"]') => [25, u'abc']

• json.loads('"abc"') => u'abc'

• json.loads('25.2') => 25.2

• json.loads('true') => True

• json.loads('null') => None

•  json.loads('{"name": "john", "age": 25, "phone": [123, 456]}')

=> {u'phone': [123, 456], u'age': 25, u'name': u'john'}

Conversion summary

JSON

Python

Object

Dictionary

Array

List

Array

Tuple (from Python)

null

None

true

True

false

False

Python dictionary => JSON object

•   Keys in Python can be number, string, or tuple.

•   Number is also converted to string.

•   But tuple (with two or more components) is not acceptable by dumps()/dump().

Working with files

• f = open('lax.json')

•  lax= json.load(f)

• out_file = open('output.json', 'w')

• json.dump(lax, out_file)