# JSON 教程
#json 概念
#
# What is JSON?
# JSON is a standard format for data exchange, which is inspired by JavaScript. Generally, JSON is in string or text format. JSON stands for JavaScript Object Notation.
#
# The syntax of JSON: JSON is written as key and value pair.
#
# {
# "Key": "Value",
# "Key": "Value",
# }
# Method Description
# # dumps() encoding to JSON objects
# # dump() encoded string writing on file
# # loads() Decode the JSON string
# # load() Decode while JSON file read
# Converting Python data to JSON is called an Encoding operation. Encoding is done with the help of JSON library method – dumps()
# dumps() method converts dictionary object of python into JSON string data format.
x = {
"name": "Ken",
"age": 45,
"married": True,
"children": ("Alice","Bob"),
"pets": ['Dog'],
"cars": [
{"model": "Audi A1", "mpg": 15.1},
{"model": "Zeep Compass", "mpg": 18.1}
]
}
json_sorted=json.dumps(x,indent=4,sort_keys=True)
json_sorted
#key字母升序
person_data = '{ "person": { "name": "Kenn", "sex": "male", "age": 28}}'
print(type(person_data))
dict_load=json.loads(person_data)
dict_load
print(type(dict_load))
#压缩编码
#When you need to reduce the size of your JSON file, you can use compact encoding in Python.
lst = ['a', 'b', 'c',{'4': 5, '6': 7}]
# separator used for compact representation of JSON.
# Use of ',' to identify list items
# Use of ':' to identify key and value in dictionary
compacx_code=json.dumps(lst,separators=[',',':'])
compacx_code
#complex对象
def complex_code(object):
if isinstance(object,complex):
return [object.real,object.imag]
raise TypeError(repr(object)+"is not right")
complex_obj=json.dumps(4+5j, default=complex_code)
print(complex_obj)
# repr() 函数将对象转化为供解释器读取的形式。
#
# 语法
# 以下是 repr() 方法的语法:
#
# repr(object)
# To decode complex object in JSON, use an object_hook parameter which checks JSON string contains the complex object or not. Example,
def iscomplex_obj2(x):
if "__complex__" in x:
return complex(x['real'],x['img'])
return x
c_object=json.loads('{"__complex__": true, "real": 4, "img": 5}',object_hook=iscomplex_obj2)
c_object
simple_object=json.loads('{"real": 6, "img": 7}',object_hook=iscomplex_obj2)
simple_object
# JSONDecoder class is used for deserialization of any Python object while performing decoding. It contains three different methods of decoding which are
from json.decoder import JSONDecoder
colour_string = '{ "colour": ["red", "yellow"]}'
JSONDecoder().decode(colour_string)
#网络结合
import requests
json_resource=requests.get("https://feeds.citibikenyc.com/stations/stations.json")
print(type(json_resource.text))
json_python=json.loads(json_resource.text)#需要格式名
print(type(json_python))
json_python
#key相同 只保留最近
repeat_pair = '{"a": 1, "a": 2, "a": 3}'
json.loads(repeat_pair)