python json基本函数介绍

# 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)

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值