Dictionary and JSON intertranslate instances in Python
- 2020-04-02 14:32:14
- OfStack
JSON is a lightweight data interchange format that is well supported in various languages. A dictionary is a data structure in Python. You can view it as an associative array.
Sometimes we need to design to dictionary convert to JSON and serialize to a file, or read JSON from a file. Just a quick note.
Dict writes to JSON to a file
#!/usr/bin/env python
# coding=utf-8
import json
d = {'first': 'One', 'second':2}
json.dump(d, open('/tmp/result.txt', 'w'))
Write the results
cat /tmp/result.txt
{"second": 2, "first": "One"}
Read the JSON
#!/usr/bin/env python
# coding=utf-8
import json
d = json.load(open('/tmp/result.txt','r'))
print d, type(d)
The results
{u'second': 2, u'first': u'One'} <type 'dict'>
other
PS: about json operation, here again for you to recommend a few more practical json online tools for your reference:
Online JSON code verification, verification, beautification, formatting tools:
(link: http://tools.jb51.net/code/json)
JSON online formatting tool:
(link: http://tools.jb51.net/code/jsonformat)
Online XML/JSON interconversion tool:
(link: http://tools.jb51.net/code/xmljson)
Json code online formatting/beautification/compression/editing/conversion tools:
(link: http://tools.jb51.net/code/jsoncodeformat)
Online json compression/escape tool:
(link: http://tools.jb51.net/code/json_yasuo_trans)
C language style /HTML/CSS/json code format beautification tool:
(link: http://tools.jb51.net/code/ccode_html_css_json)