Python-json processing

Source: Internet
Author: User

1. JSON string is

2, need to be introduced in advance, that is, import

3. Convert list/dictionary to JSON data type: Json.dumps ()

#json. Dumps (d)       #把list \ Dictionary to JSON
#json. Dumps (d,indent=8) #把list \ Dictionary into JSON, indent indent
#json. Dumps (d,indent=8,ensure_ascii=false) #可以显示这中文
Import JSON
d={' car ': {' color ': ' Red ', ' price ': ' + ', ' count ': 30},
' phone ': {' color ': ' Red ', ' price ': ' + ', ' count ': 30},
' pen ': {' color ': ' Red ', ' price ': ' + ', ' count ': 30},
' Flower ': {' color ': ' Red ', ' price ': ' + ', ' count ': 30},
' phone ': {' color ': ' Yel ', ' price ': ' + ', ' count ': 30}
}
#res =json.dumps (d) #把list \ Dictionary to JSON
#res =json.dumps (d,indent=8) #把list \ Dictionary into JSON, indent indent
Res=json.dumps (d,indent=8,ensure_ascii=false) #可以显示这中文
Print (RES)
Print (Type (res))

4. JSON data type Python type (dictionary or list): Json.loads ()

JSON data string must be double quotation marks, cannot be single quotation marks, otherwise the program error

F1=open (' F1 ', ' r ', encoding= ' utf-8 ')
Res=f1.read ()
Dict_res=json.loads (RES) #将json串 converted to a dictionary or list, based on the format of the JSON string
Print (Dict_res)
Print (Type (dict_res))

5, JSON automatic and file operation:

Json.dump (d,f1,ensure_ascii=false,indent=4)         #dump  operation file, the information is automatically written to the file, the first parameter is data, the second is a file object
#例如
#f1 =open (' F1 ', ' W ', encoding= ' utf-8 ')
# json.dump (d,f1,ensure_ascii=false,indent=4) #dump operation file, the information is automatically written to the file, the first parameter is data, the second is a file object
# json.load ()

Json.load (F1) #直接传入文件对象, will automatically read

#例如
F1=open (' F1 ', encoding= ' utf-8 ')
Print (Json.load (F1))
    

6.

7.



Python-json processing

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.