Method functions for working with JSON files in Python

Source: Internet
Author: User

1. Json.loads () converts a JSON string into a "dictionary" type in Python

Import JSON

#json串是一个字符串
f = open (' Product.json ', encoding= ' utf-8 ')

Res=f.read ()

Product_dic=json.loads (RES)

Print (Product_dic)

Operation Result:

2, Json.load () read the file for processing, the same is to convert the JSON string in the file to a dictionary type

Import JSON

#json串是一个字符串
f = open (' Product.json ', encoding= ' utf-8 ')

Product_dic=json.load (f)

Print (Product_dic)

3. Json.dumps () converts the dictionary data into a string in Python

Import JSON

Dict = {' username ': ' Sammy '}

Res=type (Json.dumps (dict))

Print (' Data type:%s '%res)

Operation Result:

Python in Json.dumps (d, Ensure_ascii=false, indent=4, Sort_keys=true)

Ensure_ascii=false indicates that the output Chinese needs to specify the ENSURE_ASCII parameter to False

Indent=4 indicates how much indentation

Sort_keys indicates whether to align

4. Json.dump () turns the dictionary data into a string in Python and writes its results to a file

Import JSON

Dict = {' username ': ' Sammy '}

Json.dump (Dict,open (' A.json ', ' W ', encoding= ' utf-8 '))

Operation Result:

Generate a A.json file

Method functions for working with JSON files in Python

Related Article

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.