简体   繁体   中英

Extracting value data from multiple JSON strings in a single file

I know I am missing the obvious here but I have the following PYTHON code in which I am trying to-

  • Take a specified JSON file containing multiple strings as an input.
  • Start at the line 1 and look for the key value of "content_text"
  • Add the key value to a new dictionary and write said dictionary to a new file
  • Repeat 1-3 on additional JSON files

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')

However, when run I receive this error:

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

Python is case-sensitive.

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

By the way, why don't you load whole file as json at once?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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