In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article introduces the relevant knowledge of "how to install and use rapidjson". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Introduction and installation of rapidjson
Rapidjson is a very good performance C++ JSON parser and serialization library, it is packaged as an expansion package of Python3, that is, in Python3, you can use rapidjson for data serialization and deserialization and parameter verification, which is very convenient and easy to use.
Rapidjson installation command: pip install python-rapidjson.
Basic use of rapidjson
Rapidjson and json modules are consistent in basic usage, except that rapidjson is not compatible with json modules in some parameters. These parameters are not commonly used. We will not introduce them too much here. For more information, please refer to the official rapidjson documentation. The basic use introduces two serialization methods, dump/dumps, and the deserialized load/loads uses the json module.
Both dumps & dump methods serialize the Python instance object into a string in JSON format, using roughly the same parameters, and the dump method has one more necessary file_like parameter than the dumps method.
Dumps () method
The result returned by this method is an instance of a Python string. There are many parameters, so here are only three parameters that are often used.
Rapidjson.dumps (obj, *, skipkeys=False, ensure_ascii=True, write_mode=WM_COMPACT, indent=4, default=None, sort_keys=False, number_mode=None, datetime_mode=None, uuid_mode=None, bytes_mode=BM_UTF8, iterable_mode=IM_ANY_ITERABLE, mapping_mode=MM_ANY_MAPPING, allow_nan=True) skipkeys
This parameter indicates whether to skip the key of the unavailable dictionary for serialization. If the default is False, if the key modified to the True dictionary is not one of the basic data types (str int float bool None), the key will be skipped and the TypeError exception will not be thrown.
Import rapidjsonfrom pprint import pprintdic = {True: False, (0,): "python"} res = rapidjson.dumps (dic) pprint (res) # TypeError: {True: False, (0,): "python"} is not JSON serializableres = rapidjson.dumps (dic, skipkeys=True) pprint (res) # "{}" ensure_ascii
This parameter indicates whether the serialized result contains only ASCII characters. The default value is True. After serializing the Python instance, all non-ASCII characters will be escaped. If the value of this parameter is changed to False, the characters will be output as is.
Dic = {"name": "name1": "lili"} res = rapidjson.dumps (dic) pprint (res) # "{" name ":" u4E3Du4E3D "," name1 ":" lili "}" res = rapidjson.dumps (dic, ensure_ascii=False) pprint (res) # "{" name ":" Lili "," name1 ":" lili "}" sort_keys "
This parameter indicates whether the key of the dictionary is sorted alphabetically when serialized. The default is False, and if you change it to True, the result of dictionary serialization is sorted alphabetically according to the dictionary's key.
Dic = {"name": "Lili", "age": "10"} res = rapidjson.dumps (dic, ensure_ascii=False, sort_keys=True) pprint (res) # "{" age ":" 10 "," name ":" Lily "}" dump () method
This method is very similar to the dumps method, except that it requires an additional necessary parameter-an file-like writable streaming object, such as a file object, that serializes the first parameter, obj, into a writable streaming object.
Rapidjson.dump (obj, stream, *, skipkeys=False, ensure_ascii=True, write_mode=WM_COMPACT, indent=4, default=None, sort_keys=False, number_mode=None, datetime_mode=None, uuid_mode=None, bytes_mode=BM_UTF8, iterable_mode=IM_ANY_ITERABLE, mapping_mode=MM_ANY_MAPPING, chunk_size=65536, allow_nan=True)
Here is the basic use of this method:
# write to the file dic = {"name": "Lili", "age": "10"} f = open ("1.py", "w", encoding= "utf8") res = rapidjson.dump (dic, f) pprint (res) # or the following usage import iostream = io.BytesIO () dump ("bar", stream) print (stream.getvalue ()) # b "bar" Validator class
The Validator class in rapidjson can be used for parameter checking. The parameter of Validator is JSON schema. When we need to know the expected fields and the representation of values in JSON data, this is the opportunity for JSON Schema to show its ability. It is a declaration format that describes the JSON data structure, and it can also be understood as the verification rules of parameters. If JSON schema is unavailable data in JSON format, an exception to JSONDecodeError is thrown.
The parameter of the class is the verification rule. If the given JSON data fails the check, a ValidationError exception is thrown. The exception consists of three parts, namely, the type of the error, the rule of the verification, and the location of the error in the JSON string.
Import rapidjsonfrom pprint import pprintvalidate = rapidjson.Validator ("{" required ": [" a "," b "]}") # indicates that parameters an and b are required validate ("{" a ": null," b ": 1}") # conforms to rule validate ("{" a ": null," c ": false}") # rapidjson.ValidationError: ("required", "#", "#") validate = rapidjson.Validator ("{" type ":" array ") "# Parameter type is array"items": {"type": "string"}, and each element type in "# array is string"minItems": 1} ") # the minimum number of elements in # array is 1validate (" ["foo", "bar"] ") # conforms to the rule validate (" [] ") # rapidjson.ValidationError: (" minItems "," # " "#")
For more parameter verification rules and definition specifications for JSON schema, please refer to * JSON schema official documentation *. The following JSON schema format is for reference only:
LOGIN_SCHEMA = {"type": "object", "properties": {"token": "string", "number": "integer"}, "required": ["token"],}} validate = rapidjson.Validator (rapidjson.dumps (LOGIN_SCHEMA)) data = {"token": "python" "number": 10} validate (rapidjson.dumps (data)) "how to install and use rapidjson" ends here Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.