Examples of conversion between dictionaries and JSON in Python

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.