在编辑器目录下面创建d.txt文件,文件内容是json字符串,格式:
[{"id":1,"name":"aaa"},{"id":2,"name":"bbb"}]
利用open()函数获得当前路径下的文件,利用read()函数读取文件数据,再用json.loads把字符串转成json格式数据。
需要引入json包
# -*- coding: utf-8 -*-
__author__ = 'zhengjiang'
import string
import json
file_object = open(r"C:\Users\John\PycharmProjects\cdyk\d.txt")
try:
all_the_text = file_object.read()
print(json.loads(all_the_text))
arr = json.loads(all_the_text)
for a in arr:
print(a)
finally:
file_object.close()
注意:不知道是什么原因,如果在桌面直接创建txt文件的话,数据无法转成json格式,系统会在我们添加的数据里面加一些东西,所以要在编辑器里面创建文件,不管是txt文件还是json文件。