JSON modules for the Python standard library family
JSON (JavaScript Object Notation) http://json.org is a subset of JavaScript syntax (ECMA-262 3rd edition) used as a lightw Eight data Interchange format.
JSON is commonly used in Web client and server data exchange, which字符串类型
The data is converted intoPython基本数据类型
or thePython基本数据类型
Converted Into字符串类型
。
Common methods
Method |
Description |
Json.loads (obj) |
Serializes a string into Python's basic data type, noting single and double quotation marks |
Json.dumps (obj) |
Serializes the basic data type of Python into a string |
Json.load (obj) |
Read a string from a file and serialize it into Python's basic data type |
Json.dump (obj) |
Serializes the basic data type of Python into a string and writes to a file |
Instance
Create a String variabledict_str
>>> dict_str = ' {' K1 ': ' v1 ', ' K2 ': ' V2 '} ' # data type is str>>> type (DICT_STR) <class ' str ' >
Serializing a string variable dict_str
into a dictionary format
>>> import json>>> Dict_json = Json.loads (DICT_STR)
View data types and output content
>>> type (Dict_json) # data type is serialized into a dictionary format <class ' dict ' >>>> dict_json{' K1 ': ' v1 ', ' K2 ': ' V2 '}
Create a listjson_li
>>> Json_li = [11,22,33,44] # data type list>>> type (json_li) <class ' list ' >
>>> import json>>> json_str = Json.dumps (Json_li)
View data types
# for Str>>> type (JSON_STR) <class ' str ' >>>> json_str ' [11, 22, 33, 44] '
# Create a dictionary data type >>> dic = {"K1": 123, "K2": 456}# output Type and content >>> print (type (DIC), DIC) (<type ' dict '), {' K2 ': 456, ' K1 ': 123} # import JSON modules >>> imports json# convert dic to a string and write to the db file under the current directory, if not, create >>> json.dump ( Dic,open ("DB", "W")) # import OS Module View >>> import os# view files under current directory >>> Os.system ("ls-l") Total 8-rw-r--r--1 root Root 23:54 db0# View the contents of the file db that, the last 0 is the command execution success >>> Os.system ("Cat db") {"K2": 456, "K1": 123}0
# Read the db file below the current directory, convert the content to Python's basic data type and assign it to result>>> result = Json.load ("Open (" db "," R ")) # View the data type and contents of object result >>> Print (type (result), result) (<type ' dict '), {u ' K2 ': 456, U ' K1 ': 123})
#Python标准库 #Json
JSON module of 5Python standard Library series