python当中json相关知识

2019-08-17  本文已影响0人  慕慕她爸

json基本概念

python-json数据类型对应关系

python数据类型 json数据类型
dict object
list,tuple array
str str
int,float num
True true
False false
None null

常见操作

  1. python数据转换为json对象
  2. json字符串转换为python对象
  3. 从文件中读取json字符串,转换为python对象
#coding:utf-8

import json

def python_to_json():
    """
    将python对象转换为json
    :return:
    """
    d = {
        'name':  'python书籍',
        'price': 777,
        'is_valid': True
    }
    rest = json.dumps(d, indent=4)
    print(rest)

def json_to_python():
    """
    将json字符串转换为python字符串
    :return:
    """
    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'])

def json_to_python_from_file():
    """
    从文件读取内容,并转换成python对象
    :return: 
    """
    with open('book.json', 'r', encoding='utf-8') as f:
        s = f.read()
        print(s)
        rest = json.loads(s)
        print(rest)
        print(rest['name'])
    f.close()


if __name__ == '__main__':
    python_to_json()
    json_to_python()
    json_to_python_from_file()

注意事项

上一篇 下一篇

猜你喜欢

热点阅读