A Brief Introduction to JSON usage in Python and a brief introduction to pythonjson
JSON advanced
Python dict objects can be directly serialized into JSON {}. However, many times we prefer to use class to represent objects, such as defining the Student class, and then serialize:
import jsonclass Student(object): def __init__(self, name, age, score): self.name = name self.age = age self.score = scores = Student('Bob', 20, 88)print(json.dumps(s))
Run the code and get a TypeError without
in the Web page, very convenient.JSON represents objects that are standard JavaScript language objects, and JSON and Python have built-in data types that correspond to the following:
JSON type
Python type
{}
Dict
[]
List
"String"
' Str ' or U ' Unicode '
1234.56
int or float
True/false
True/false
Null
None
Python's built-in json modules provide
])'wzesmiwzldrd.wsphqc0gr7vuqivlsukj0ietdgo' >>> s.loads ('wzesmiwzldrd.wsphqc0gr7vuqivlsukj0ietdgo') [1, 2, 3, 4]VI. JSON Web SignatureJSON Web Signatures Starting with "itsdangerous" 0.18 JSON Web Signatures is also supported. They generally work very similar to the already existing URL safe serializer but would emit headers according to the Curren T Draft (Ten) of the JSON Web Signature (JWS) [ Draft-ietf-jose-json-web-signature ]. from Import Jsonwebsignatureserializer>>> s = Jsonwebsignat
;> sys.getdefaultencoding()‘utf-8‘>>> sys.getfilesystemencoding()‘mbcs‘
1
2
3
4
5
2. JSON moduleJSON (JavaScript Object Notation) is a lightweight data interchange format. Easy for people to read and write. It is also easy for machine parsing and generation.The data format can be easily understood as a collection of key-value pairs (A collection of name/value pairs). In different languages, it is understood as objects (object), record (record), structure (struct), D
" "module: Contains Python definition and declaration of the file, a py file is a Module 1, built-in module Python interpreter comes with Module 2, extension module, the module developed by Daniel, need to download using 3, custom module of the module itself * * * * Serialization module JSON Pickle Shelvejson can be used to serialize data types in different languages into strings, support str,list,dict,bool These data types pickle only available in the Python language, and support all Python dat
absolute path to the current fileOs.path.dirname: Gets the parent directory of the current file . Sys.path.append (Lujin): Adds the acquired path to the system environment variable. 3. Import optimization(1) Import module_nameModule_name.name (). The essence: First find the module, looking for the method under the module . "Finding more is inefficient. "(2) from module_name import nameName (): essence: Take the method in the module to the specified position to execute it again. The process of
that when the file is opened open() with UTF-8 encoding Open, at dump() the time also add ensure_ascii=false, Otherwise it will become ASCII code written to the JSON filejson.dump(all_house,f,ensure_ascii=False,sort_keys=True, indent=4)
Json.dumps ()/json.loads () etc usagejson_str = json.dumps(all_house,ensure_ascii=False); #all——books 为列表、字典等python自带的数据结构,将其写成json#print json_str; #[{"brokername": "王东宇"},{},{}]new_dict = json.loads(json_str);#主要是读json文件时,需要用到#print new_dict; #{u'house_are
First, what is called serialization The process of converting an original dictionary, list, and other content into a string is called serialization.Second, the purpose of serialization1. Persist the custom object in some form of storage;2. Transfer objects from one place to another.3, make the program more maintenance.ThreeOnly strings can be written to the fileOnly bytes---strings that can be transmitted over the networkConverts the content to be transmitted and the contents to be stored into
One, the JSON module1. DefinitionThe process of converting dictionaries, lists, and so on into strings is serialization.The operation has a limited data type, but can support all programming language operations. 2, why should there be serialization?1. Persist the custom object in some form of storage.2. Passing objects3, is the program more maintenance3. Four functions (Dumps,loads,dump,load)Dumps loads I
that when the file is opened open() with UTF-8 encoding Open, at dump() the time also add ensure_ascii=false, Otherwise it will become ASCII code written to the JSON filejson.dump(all_house,f,ensure_ascii=False,sort_keys=True, indent=4)
Json.dumps ()/json.loads () etc usage
json_str = json.dumps(all_house,ensure_ascii=False); #all——books 为列表、字典等python自带的数据结构,将其写成json#print json_str; #[{"brokername": "王东宇"},{},{}]new_dict = json.loads(json_str);#主要是读json文件时,需要用到#print new_dict; #{u'house_are
declared, then use the user name that originated the connection.-A--data-onlyOnly output data, no output mode (data definition).This option is only meaningful for plain text formatting. For the archive format, you can declare options when calling Pg_restore.-B--blobsContains large objects in the dump. You must select a non-text output format.-C--cleanOutputs the command to clean (delete) The database object before creating the database Creation command.This option is only meaningful for plain t
--add-drop--database adds a drop DATABASE statement before each CREATE DATABASE statement. --add-drop-tables adds a drop TABLE statement before each CREATE TABLE statement. --add-locking uses the lock tables and unlock tables statements to refer to each table dump. Reload the dump file when it is inserted faster. --all--database,-a dumps all tables in all databases. In the same way that you use the---database option, name all databases on the command
{}
Dict
[]
List
"String"
Str
1234.56
int or float
True/false
True/false
Null
None
Python's built-in json modules provide a very sophisticated translation of Python objects into JSON format. Let's look at how to turn the Python object into a JSON:Import JSON>>> d = dict (name='Bob', age=20, score=88)>>> Json.dumps (d) ' {"Age": +, "score": "," "Name": "Bob"} '
Python json serialization deserialization and Chinese Encoding
In a project, you need to obtain a json-format data from the cloud, save it to a local file, and then read it out. In this case, you need to use the json dumps method and loads method, to achieve data serialization and deserialization. Specifically, the dumps method can set the data sequence in json format to the related data type of python, whi
read out to form an object. How do---serialize?Two modules are available in Python for serialization. Are pickle and JSON, respectively.PicklePickle is a unique serialization module in Python, so-called exclusive, which means that it cannot interact with the serialization of other programming languages because pickle converts the data object to bytesImport Pickle>>> d=[1,2,3,4]>>> pickle.dumps (d) b'\x80\x03]q\ X00 (k\x01k\x02k\x03k\x04e. '>>> type (pickle.dumps (d))class'bytes' > #类型为byte
, we use python, python has a modifier for functions.
So the implementation scheme is as follows:
Define a decorator. If the data is obtained before, the data in the cache is directly obtained. If the data is not obtained before, the data is pulled from the website and saved to the cache.
The Code is as follows:Copy codeThe Code is as follows:Def get_dump_data (dir_name, url ):M = hashlib. md5 (url)Filename = m. hexdigest ()Full_file_name = \ 'dumps/%
JSON Advanced
Python's Dict object can be serialized directly into the JSON {}, but, many times, we prefer to use class to represent objects, such as defining the student class, and then serializing:
Import Jsonclass Student (object): def __init__ (self, name, age, score): self.name = name self.age = Age Self.score = scores = Student (' Bob ', ', ') print (Json.dumps (s))
Run the code and relentlessly get a typeerror:
Traceback (most recent): ... TypeError:
The reason for the error
obtained data and retrieve it directly from the cache when necessary.
OK. the target already exists. how can this problem be achieved?
If it is in C ++, this is a very troublesome thing, and the code written must be ugly, but fortunately, we use python, python has a modifier for functions.
So the implementation scheme is as follows:
Define a decorator. if the data is obtained before, the data in the cache is directly obtained. if the data is not obtained before, the data is pulled from the webs
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.