Python JSON format file read and write

Source: Internet
Author: User
Tags serialization python list

serialization (serialization): converts the state information of an object (such as Python's simple data type list, String,dict,tuple,int,float, Unicode) into something that can be stored or transmitted, such as JSON, XML format) process

deserialization: reads the state of the object that needs to be deserialized from the storage file or storage area (JSON, XML), and rebuilds the object


JSON (JavaScript Object notation): A lightweight data interchange format that is simpler, easier to read, write, parse, and generate than XML, and JSON is a subset of JavaScript


The JSON module is integrated in Python

Serialization: enconding--Converts a Python object encoding into a JSON string

deserialization: decoding--converts a JSON string decoding into a Python object

There are Jsonencode and jsondecoder two classes in the JSON package to implement the conversion of JSON string and dict type data



Example: Serialization mode: (a control diagram of a Python object converted to JSON)


Import JSON

Data={' A ': 1, ' B ': 2, ' C ': 3}#或者data =[' A ', ' B ', ' C ', 1,3] or data= (3,3,4,5) and other Python objects can be

F=open ("./test.txt", "W")

Data_string=json.dumps (data)#方式1

F.write (data_string)

F.write (' \ n ')#write不会在自动行末加换行符, need to manually add

Sort_data_string=json.dumps (data,sort_keys=true)#方式1, the dictionary is encoded in the keys order

F.write (sort_data_string)

F.write (' \ n ')

Json.dump (data,f)#方式2, note that dump does not have s

F.write (' \ n ')

F.close ()


deserialization: (The JSON object is converted to a control diagram of a Python object)


F=open ("./test.txt", "R")

For line in F:

Decodes=json.loads (line)

Print type (decodes)

Print decodes #输出key前会带一个u, similar to [{u ' a]: U ' a ', U ' C ': 3.0, U ' B ': [2, 4]}]

F.close ()


Additional:dumps (data, indent=2) indent parameters are indented and read more clearly as they appear:

Dumps (data, separators): The function of the separators parameter is to remove,,: The next space, from the above output can see,: "There is a space behind, this is to beautify the effect of the output, but in the process of our data transfer, the more concise the better, Everything that's redundant is removed, so you can add

Example:

Import JSON
data = [{' A ': ' A ', ' B ':(2,4), ' C ': 3.0}] #list对象


data_string = json.dumps (data)
Print "encoded:", data_string


decoded = Json.loads (data_string)
Print "decoded:", decoded


Print "ORIGINAL:", type (data[0][' B '])
Print "Decoded:", type (decoded[0][' B '])
Output:


Encoded: [{"A": "A", "C": 3.0, "B": [2, 4]}]
Decoded: [{u ' a ': U ' a ', U ' C ': 3.0, U ' B ': [2, 4]}]
ORIGINAL: <type ' tuple ' >
Decoded: <type ' list ' >
In the decoding process, the JSON array is eventually converted to the Python list, not the original tuple type


during the encoding process, the key of the Dict object can only be a string object, and if it is a different type, the ValueError exception is thrown in the encoding process. Skipkeys can skip processing of a key that is not a string object.


Import JSON


Data= [{' A ': ' A ', ' B ':(2, 4), ' C ': 3.0, (' d ',): ' D tuple '}]


Try:
&nb Sp   Print json.dumps (data)
except (TypeError, ValueError) as err:
    print ' ERROR: ', err
PRINT&N Bsp
Print json.dumps (data, skipkeys=true)
Output:


Error:keys must be a string


[{"A": "A", "C": 3 .0, "B": [2, 4]}]

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.