Day17-json format Conversion

Source: Internet
Author: User

JSON introduction: JSON, full name JavaScript Object Notation, is a lightweight data interchange format. The most extensive application of JSON is the data format for the communication of Web servers and clients in Ajax. It is also often used in HTTP requests, so it is natural to learn a variety of JSON. And we're going to take the two most long-run ways we usually work.

Four ways to use JSON modules

# Four methods of JSON
# json.loads
# Json.dumps
# More S is the processing of strings, no more s is the processing of files
# Json.load
# Json.dump
#four methods of JSON#json.loads#Json.dumps#multi-S is the processing of strings, no more s is the processing of files#Json.load#Json.dump#loads loading is the conversion of JSON into other formats, strings or text-related#dumps upside down is to convert other image formats into JSON format#The load must have been extracted from the file with JSON data, and load must have converted the file into JSON data .#dump is the writing of JSON data to a file#Example 1: Convert the Python dic format to JSON formatImportJsona= Dict (name='WXP', gae=25,message='You is so cool')Print(a)Print(Type (a)) b=Json.dumps (a)Print(type (b))Printb#example 2:json format converted to dict formatC=Json.loads (b)Print(Type (c))Print(c) Output results:<type'Dict'><type'Str'>{"message":"You is so cool","Gae": 25,"name":"WXP"}<type'Dict'>{u'message': U'You is so cool'+ R'Gae': +, U'name': U'WXP'}#Example 3: Writing JSON to a fileJsondata ='{"A": 1, "B": 2, "C": 3, "D": 4}'With Open ('a.txt','W') as F:json.dump (jsondata,f)#Example 4: Reading from a file to JSONWith open ('a.txt') as Fr:m=Json.load (FR)Print(m)Print(Type (m)) The output can be found in A.txt as follows:"{\ "a\": 1,\ "b\": 2,\ "c\": 3,\ "d\": 4}"#Screen Output Example 4{"a": 1,"b": 2,"C": 3,"D": 4}<type'Unicode'>Note The general default input Unicode format encoding

Day17-json format Conversion

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.