19-01-09json数据

2019-01-09  本文已影响0人  one丨

json

1.什么是json数据

2.json数据的语法

3.json支持的数据类型

4.python处理json数据

python中提供了json模块,专门用来处理json数据

1, 将json数据转换成python数据(通过爬虫获取到别人提供的json数据,在python中处理)

2,将python数据转换成json数据(python写后台接口将数据提供给客户端)

5.json文件处理

严格来说,json文件是文件内容是json数据的文件

import json(导入json模块)

def main():(格式,方便整段代码以后带入其他代码内)

======3.读json文件========

with open('data.json', encoding='utf-8') as f:
    result = json.load(f)   # 相当于 result = json.loads(f.read())
    print(type(result), result['msg'])

all_student = [
    {'name': '小明', 'age': 12, 'tel': '1237736'},
    {'name': 'yuting', 'age': 18, 'tel': '23333'},
    {'name': 'Luffy', 'age': 20, 'tel': None},
    {'name': 'zuoLuo', 'age': 30, 'tel': '923736'},
]
with open('student.json', 'w', encoding='utf-8') as f:
    json.dump(all_student, f)  # 相当于 f.write(json.dumps(all_student))

print(' ===============2.python转json===============')
result = json.dumps(100.23)
print(type(result), result)    # '100.23'

result = json.dumps('abc')
print(type(result), result)  # '"abc"'

result = json.dumps(True)
print(type(result), result)  # 'true'

result = json.dumps([10, 'abc', True, None])
print(type(result), result)  # '[10, "abc", true, null]'

result = json.dumps((10, 'abc', True, None))
print(type(result), result)  # '[10, "abc", true, null]'

result = json.dumps({'a': 10, 'b': 'abc', 'c': True, 'd': None})
print(type(result), result)  # '{"a": 10, "b": "abc", "c": true, "d": null}'

# 集合不能转换成json数据
# result = json.dumps({10, 'abc', True, None})
# print(type(result), result)  # '[10, "abc", true, null]'


# ===============1.json转python===============
print('===========================')
# 将json中的字符串转换成python数据
content = json.loads('"abc"', encoding='utf-8')
print(content, type(content))   # abc <class 'str'>

# 将json中的数字转换成python数据
content = json.loads('100', encoding='utf-8')
print(content, type(content))

# 将json中的字典转换成python数据
message = '{"name": "张三", "age": 18, "sex": null, "marry": true}'
content = json.loads(message, encoding='utf-8')
print(content, type(content))
print(content['name'])

# 练习1
with open('data.json', encoding='utf-8') as f:
    info = f.read()
    # print(type(info), info)
    dict1 = json.loads(info, encoding='utf-8')
    for item in dict1['data']:
        print(item['url'])
image.png
all_student = 空
add_student()
import json


def add_student(list1: list):
    name = input('姓名:')
    age = int(input('年龄:'))
    score = float(input('成绩:'))
    list1.append({'name': name, 'age': age, 'score': score})


def main():
    # 获取数据
    # all_student = []
    with open('allStudent.json', encoding='utf-8') as f:
        all_student = json.load(f)
        # all_student = [{}, {}]

    add_student(all_student)
    add_student(all_student)
    # all_student = [{}, {}, {}, {}]

    # 更新数据
    with open('allStudent.json', 'w', encoding='utf-8') as f:
        json.dump(all_student, f)

    print(all_student)


if __name__ == '__main__':
    main()
上一篇下一篇

猜你喜欢

热点阅读