Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does python parse JSON

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

Most people do not understand the knowledge points of this "python how to analyze JSON" article, so the editor summarizes the following content, detailed content, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "python how to analyze JSON" article.

Brief introduction

The JSON module is python's built-in module for serializing and deserializing python objects.

Serialization refers to the conversion of python objects to data streams in json format, while deserialization converts data streams in json format to python objects.

There are four methods commonly used in this module:

Json.dump serializes Python objects into data streams in Json format and writes them to objects of file type

Json.dumps serializes Python objects into strings in Json format

Json.load reads data in Json format from objects of file type and deserializes them into Python objects

Json.loads deserializes a string containing data in Json format into a Python object

The two dump functions convert python objects to json, which can be understood as encoding (similar to demjson's encode function), and the two load functions convert json to python objects, which can be understood as JSON parsing (similar to demjson's code function). Because the functions of two dump and two load are similar, the editor only introduces one of them (introduces the encoding and parsing of strings in JSON format, that is, the dumps and loads functions).

Json.dumps ()

The parameters that dumps can pass are as follows:

Json.dumps (obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False)

In daily use, in more cases, we only pass the necessary obj parameters (this is an object), and the other parameters are optional. The following table shows the function of all the parameters of the function:

Parameter action obj (required) whether the python object skipkeys=False to be serialized skips the key of dictionary elements in the object to serialize that is not a primitive type of data

If True, skip, and if False, a TypeError exception is thrown. Whether ensure_ascii=True escapes non-ascii characters in the string in the object to be serialized.

If the parameter is True, non-ascii characters in the string are escaped into unicode strings, otherwise, they will not be escaped.

Whether check_circular=True does circular reference checking for container types.

If this parameter is set to False, no check is performed, but an OverflowError or more serious case may occur.

If this parameter is set to True, a circular reference check of the container type is performed and an exception is thrown when a circular reference is found.

Whether allow_nan=True allows serialization of values of type float that are out of range (such as float ('inf'), float ('-inf'), float ('nan')).

If this parameter is set to True, the values listed above will be replaced by the equivalent values in JavaScript (Infinity,-Infinity, NaN) in turn

If this parameter is set to False and those out-of-range values appear in the object to be serialized, a ValueError exception is thrown.

Whether indent=None adds indentation in front of array elements and object members to make the format more beautiful.

If this parameter is set to an integer greater than or equal to 1, a newline character and a corresponding number of spaces are added to indicate indentation, if set to 0, only newline characters are added, and if set to None, there is no indentation.

Separators=None sets the separator between items in Json and between keys and values of objects

The parameter must be a 2-tuple, the first element of the tuple represents the delimiter between items in the Json data, and the second element of the tuple represents the delimiter between the key and value of the Json object. The default delimiter is (',',':')

Default=None specifies a function that converts a non-serializable Python object into a serializable Python object. Cls=None specifies a subclass of a custom JSONEncoder (for example, overrides the. default () method to serialize additional types), using the cls keyword parameter when specifying this parameter. If this parameter is not specified, the default JSONEncoder is used. Whether sort_keys=False wants to sort dictionary elements in the object by key.

The default is False, that is, no sorting, if specified as True, sorting will be done.

Take a simple example (the following is an example of an article in which the json.dumps method is used):

From flask import Flaskimport jsonapp = Flask (_ _ name__) @ app.route ('/ hello') # specifies url and executes the annotated function def hello_world () when the requested url is / hello: data = {'no': 1,' name': 'W3C schoolrooms,' url': 'http://www.yisu.com'} # in python, the data format corresponding to json is a dictionary So here we create a dictionary to store data and return print (type (data)) # print, make sure that the data type is the dictionary json_str = json.dumps (data) # use dumps to convert the dictionary type to a string, so that it can be returned through the http protocol # json is transmitted as a string return json_str # using flask You can return this string directly with return, and you can return json to if _ _ name__ = ='_ _ main__': app.run () # to run the flask project

The following conversion rules are followed when converting python objects to JSON strings:

PythonJsondictobjectlist, tuplearraystrstringint, floatnumberTruetrueFalsefalseNonenulljson.loads ()

The parameters that loads can pass are as follows:

Json.loads (cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None)

In daily use, in more cases, we only pass the necessary s parameters (this is a string), and the other parameters are optional. The following table shows the function of all the parameters of the function:

Parameter action s (required) JSON string encoding=None to be deserialized

This parameter has been deprecated and cls=None will be ignored

Specify a custom JsonDecoder subclass to implement specific deserialization requirements; object_hook=None

Accepts a callable object that handles the value of type dict in the decoded Python object.

Note that this process is recursive, that is, all dictionary structures within the returned Python object will be handled by this method.

Parse_float=None

The value used to process the float type in the decoded Python object.

Parse_int=None accepts a callable object that handles the value of type int in the decoded Python object. Parse_constant=None accepts a callable object for processing Infinity,-Infinity, NaN, or other illegal Json values when decoding.

If object_parse_hook=None specifies this parameter and sets it as a callable object, the Json object is decoded into a list of elements that are binary, the two elements of which are the keys and values of the key-value pairs in the Json object, and the order of the elements in the list is the same as the order of the key-value pairs in the Json object.

Take a simple example (the following is an example of an article in which the json.loads method is used, and it happens to be a sister article with the previous article, but although it is a sister article, it is not the same project, that is, the JSON data is not requested by the previous project):

Import requestsimport jsonresponse = requests.get ('http://www.kuaidi100.com/query?type=ems&postid=111111111111')# requests a json using request The express order number here is print (response) print (type (response)) # printed by the editor and found to be an object response = response.text# using requests's text method to pull out the response text print (response) print (type (response)) # and found to be a string after printing (JSON is transmitted as a string) response = json.loads (response) # using the loads method of JSON module This string can be encoded. Print (response) print (type (response)) # prints the result and finds that it is a dictionary (JSON corresponds to the object of JavaScript, corresponding to the dictionary of python, corresponding to the map of java) response = json.dumps (response) # using JSON's dumps method, the dictionary can be converted into a string (the transmission of JSON is transmitted as a string,) print (response) print (type (response))

Similar to the serialization process, the conversion of JSON to python objects follows certain rules:

JsonPythonobjectdictarrayliststringstrnumber (int) intnumber (real) floattrueTruefalseFalsenullNone above is about the content of "how python interprets JSON". I believe we all have some understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report