Conversion of dictionary and JSON in Python, pythonjson
JSON 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
Copy codeThe 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
Copy codeThe Code is as follows:
Cat/tmp/result.txt
{"Second": 2, "first": "One "}
Read JSON
Copy codeThe 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
Copy codeThe Code is as follows:
{U'second': 2, u'first': u'one'} <type 'dict '>
Others