python读取json数据并筛选存入新的json文件

数据格式说明:

{
	"TagList": [
		{
			"TagID": 12,
			"TagName": "LeftStop",
			"DeviceID": 2,
		},
…………………………
		{
			"TagID": 13,
			"TagName": "LeftStart",
			"DeviceID": 2
		}
    ]
}

读取json文件

import json

# 读取 JSON 数据
with open("Tag.json",'r') as load_f:
    load_dict = json.load(load_f)

这里报错,'gbk' codec can't decode ,转码解析的问题。参考链接

open("Tag.json",'r',encoding='utf-8')中加上encoding='utf-8'

创建新字典筛选json字段加入

newdata = []
x=-1
for i in load_dict['TagList']:
    x += 1
    tagid = load_dict['TagList'][x]['TagID']
    tagname = load_dict['TagList'][x]['TagName']
    deviceid = load_dict['TagList'][x]['DeviceID']
    keydict = {"TagID":tagid, "TagName":tagname,"DeviceID":deviceid}
    newdata.append(keydict)

将字典转化为json格式,写入新文件

newjson = json.dumps(newdata, indent=4,separators=(',', ': '))
f = open('newTag.json', 'w')
f.write(newjson)
f.close()

参考1-菜鸟教程;

参考2-另一个博主

你可能感兴趣的:(学习笔记,json,python,开发语言)