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

2024-09-27 19:19:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道我在这里忽略了显而易见的东西,但是我有下面的PYTHON代码,我正在尝试-

  • 将包含多个字符串的指定JSON文件作为输入。你知道吗
  • 从第1行开始,查找“content\u 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'

Tags: 文件textjsonget字典myresultcontent
1条回答
网友
1楼 · 发布于 2024-09-27 19:19:41

Python区分大小写。你知道吗

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

顺便问一下,为什么不一次将整个文件作为json加载?你知道吗

相关问题 更多 >

    热门问题