繁体   English   中英

从单个文件中的多个JSON字符串中提取值数据

[英]Extracting value data from multiple JSON strings in a single file

我知道我在这里找不到明显的地方,但是我尝试使用以下PYTHON代码-

  • 将包含多个字符串的指定JSON文件作为输入。
  • 从第1行开始,查找“ content_text”的键值
  • 将键值添加到新字典并将该字典写入新文件
  • 在其他JSON文件上重复1-3

import json
def OpenJsonFileAndPullData (JsonFileName, JsonOutputFileName):
    output_file=open(JsonOutputFileName, 'w')
    result = []
    with open(JsonFileName, 'r') as InputFile:
        for line in InputFile:
            Item=json.loads(line)
            my_dict={}
            print item
            my_dict['Post Content']=item.get('content_text')
            my_dict['Type of Post']=item.get('content_type')
            print my_dict
            result.append(my_dict)
    json.dumps(result, output_file)

OpenJsonFileAndPullData ('MyInput.json', 'MyOutput.txt')

但是,运行时我收到此错误:

AttributeError: 'str' object has no attribute 'get'

Python区分大小写。

Item = json.loads(line)  # variable "Item"
my_dict['Post Content'] = item.get('content_text')  # another variable "item"

顺便说一句,为什么不立即将整个文件加载为json?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM