Sainita
Sainita

Reputation: 362

How to extract a single Key value from a JSON file?

This is my output.json file:

{
    "ParsedResults": [
        {
            "TextOverlay": {
                "Lines": [],
                "HasOverlay": false,
                "Message": "Text overlay is not provided as it is not requested"
            },
            "TextOrientation": "0",
            "FileParseExitCode": 1,
            "ParsedText": "180 Grade IV\r\n\u0103\u021ar: Class VIII Pass\r\nwww.facebook.com, Since 2012\r\n",
            "ErrorMessage": "",
            "ErrorDetails": ""
        }
    ],
    "OCRExitCode": 1,
    "IsErroredOnProcessing": false,
    "ProcessingTimeInMilliseconds": "343",
    "SearchablePDFURL": "Searchable PDF not generated as it was not requested."
}

I am trying to get the ParsedText value from this JSON file.

This is my the code I am using:

import json
    
f = open('output.json',)
data = json.load(f)
print(data['ParsedResults']['TextOverlay']['ParsedText'])
f.close()

Facing this error:

TypeError: list indices must be integers or slices, not str

How to read that particular value from ParsedText, please guide. Thanks in Advance

Upvotes: 1

Views: 1099

Answers (2)

Fatemeh Mansoor
Fatemeh Mansoor

Reputation: 565

ParsedResults is not an object, it's a list

try this:

import json

f = open('output.json',)
data = json.load(f)
print(data['ParsedResults'][0]['ParsedText'])
f.close()

Upvotes: 2

Jisson
Jisson

Reputation: 3725

data['ParsedResults'] is a list, you need to use the index to parse, So you are getting TypeError: list indices must be integers or slices, not str

use data['ParsedResults'][0].

use the following,

import json
f = open('output.json',)
data = json.load(f)
print(data['ParsedResults'][0]['TextOverlay']['ParsedText'])
f.close()

Upvotes: 1

Related Questions