Home > Blockchain >  How to read file JSON with json.loads
How to read file JSON with json.loads

Time:12-09

I want to get "ocr_text" in this json

How can I get ocr_text ex:json.loads(response.text)["name"]

{
    "name": "jane doe",
    "salary": 9000,
    "skills": [{
        "Raspberry pi":" MHSO",
        "Machine Learning": "MHSO",
        "Web Development": "uaskdj",
        "ocr_text": "MH 02 CB 4545"
    }],
    "email": "[email protected]",
    "projects": [
        "Python Data Mining",
        "Python Data Science"
    ]
}

CodePudding user response:

import json

jsonstr = '{ "name": "jane doe", "salary": 9000, "skills": [{ "Raspberry pi":" MHSO", "Machine Learning": "MHSO", "Web Development": "uaskdj", "ocr_text": "MH 02 CB 4545" }], "email": "[email protected]", "projects": [ "Python Data Mining", "Python Data Science" ] }'
j = json.loads(jsonstr)

ocr = j["skills"][0]["ocr_text"]

CodePudding user response:

Paste that into the python shell and experiment

>>> data = {
...     "name": "jane doe",
...     "salary": 9000,
...     "skills": [{
...         "Raspberry pi":" MHSO",
...         "Machine Learning": "MHSO",
...         "Web Development": "uaskdj",
...         "ocr_text": "MH 02 CB 4545"
...     }],
...     "email": "[email protected]",
...     "projects": [
...         "Python Data Mining",
...         "Python Data Science"
...     ]
... }
>>> 
>>> data["skills"]
[{'Raspberry pi': ' MHSO', 'Machine Learning': 'MHSO', 'Web Development': 'uaskdj', 'ocr_text': 'MH 02 CB 4545'}]
>>> data["skills"][0]
{'Raspberry pi': ' MHSO', 'Machine Learning': 'MHSO', 'Web Development': 'uaskdj', 'ocr_text': 'MH 02 CB 4545'}
>>> data["skills"][0]["ocr_text"]
'MH 02 CB 4545'

There you go. That'll get you the first ocr_text in the list. It will error if there are no items in the list. And it doesn't deal with the likelyhood that there is more than one data item in that list.

  • Related