Conversion of JSON string to Python type (dictionary)

Source: Internet
Author: User

A. JSON into a dictionary:

Product.json file: Converts the contents of the file into a Python dictionary, as follows:

Method one: Use. Loads (), read first and then convert

Import JSON #导入json, note: The JSON string is a string

f = open (' Product.json ', encoding = ' utf-8 ')

res = F.read ()

Product_dic = json.loads (res) #把json串, into Python data type, dictionary

Print (pruduct_dic) #如结果:

Method two: Use. Load (File object), automatically read the file and convert

f = open (' Product.json ', encoding = ' utf-8 ')

Product_dic = Json.load (f) #传一个文件对象, load () is an automatic read and convert file

Print (product_dic) #如结果:

Two. Dictionary converted to JSON string

Method one:. Dumps (dictionary name)

The dictionary is as follows:

FW = open (User_info.json ', ' w ', encoding = ' utf-8 ')
Dic_json = Json.dumps (d,ensure_ascii=false,indent=4) #字典转化成json, the dictionary is converted into a string. Which, D, dictionary; ensure_ascii=false processing Chinese, remove the words will be garbled, Indent=4,json format indent bytes
Fw.write (Dic_json)
The results are as follows:

Method two:. Dump (dictionary name)

FW = open (User_info.json ', ' w ', encoding = ' utf-8 ')
Dic_json = Json.dump (d,fw,ensure_ascii=false,indent=10) #直接操作文件, do not write
View the file results as follows:



Conversion of JSON string to Python type (dictionary)

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.