利用Python互转Json数据格式

一、将Python对象转换成json对象

import json
def python_to_json():
    """ 将python对象转换成json """
    d = {
        'name': 'python书籍',
        'price': 62.3,
        'is_valid': True
    }
    rest = json.dumps(d, indent=4) //设置首行缩进
    print(rest)

二、将json转换成python

def json_to_python():
""" 将json转换成python """
data = '''
    {
        "name": "Python书籍",
        "origin_price": 66,
        "pub_date": "2018-4-14 17:00:00",
        "store": ["京东", "淘宝"],
        "author": ["张三", "李四", "Jhone"],
        "is_valid": true,
        "is_sale": false,
        "meta": {
            "isbn": "abc-123",
            "pages": 300
        },
        "desc": null
    }
'''
rest = json.loads(data)
print(rest)
print(rest['name'])

三、从文件读取内容,并转换成python对象

def json_to_python_from_file():
    """ 从文件读取内容,并转换成python对象 """
    f = open('./static/book.json', 'r', encoding='utf-8') 以只读的格式,utf-8 的编码读取
    s = f.read()
    print(s)
    rest = json.loads(s)
    print(rest['name'])
    f.close()  //打开文件后一定要关闭

你可能感兴趣的:(Python学习)