python 读取文件, 转化为 json 格式, 获取 json 中某个属性的值

需求描述

有以下文件 info.txt, 想要读取其中的 fileVideoId, 组成一个列表后返回.

[{"source":1,"fileVideoId":10001,"videoId":"ks009182837mgsciro","materialId":190929}]
[{"source":1,"fileVideoId":10002,"videoId":"ks009182837mgsciro","materialId":190930}]
[{"source":1,"fileVideoId":10003,"videoId":"ks009182837mgsciro","materialId":190931}]
[{"source":1,"fileVideoId":10004,"videoId":"ks009182837mgsciro","materialId":190932}]

代码

import json
json_path = "info.txt"
fileVideoIds = []
# 读取 json 日志文件
with open(json_path, 'r') as load_f:
	# 读取文件
    lines = load_f.readlines()
    # 处理每一行的 json 内容
    for line in lines:
    	# 将数据转为 json
        arr = json.loads(line)
        # 处理数组中每一个元素
        for data in arr:
            fileVideoIds.append(data.get('fileVideoId'))

print(fileVideoIds)

运行结果:

[10001, 10002, 10003, 10004]

你可能感兴趣的:(python,json)