This article describes examples of conversion between dictionaries and JSON in Python. This article provides examples of conversion from Dict to JSON, reading JSON, and converting to Dict, for more information, see JSON. it is a lightweight data exchange format with good support in various languages. A dictionary is a data structure of Python. It can be seen as an associated array.
Sometimes we need to design a dictionary to convert to JSON to serialize to a file, or read JSON from the file. Easy to forget.
Dict to JSON to write files
The code is as follows:
#! /Usr/bin/env python
# Coding = UTF-8
Import json
D = {'first': 'one', 'second': 2}
Json. dump (d, open ('/tmp/result.txt', 'w '))
Write result
The code is as follows:
Cat/tmp/result.txt
{"Second": 2, "first": "One "}
Read JSON
The code is as follows:
#! /Usr/bin/env python
# Coding = UTF-8
Import json
D = json. load (open ('/tmp/result.txt', 'r '))
Print d, type (d)
Running result
The code is as follows:
{U'second': 2, u'first': u'one '}
Others