Home > OS >  How to parse mulitple Json Arrays with the same name in Python
How to parse mulitple Json Arrays with the same name in Python

Time:06-15

I want to parse a Json File where all Json Arrays have the same Name just as the following:

[
    {
        "envelope": {
            "source":"user1",
            "data":{
                "message": "Hello World 0"
            }
        }
    },
    {
        "envelope": {
            "source":"user1",
            "data":{
                "message": "Hello World 1"
            }
        }
    }, 
    ...
]

And this is my code so far:

def check_messages():
    data = requests.get(urlWhereIGetJson)
    for d in data:
        message = d['envelope']['data']['message']
        print(message)
    

My code is only giving me back the first entry. ("Hello World 0") but I need every message.

I hope somebody can teach me and show how to parse the json correctly. I am not able to edit the JSON File.

I'm sorry for my english

CodePudding user response:

Here is what you need

response = requests.get(urlWhereIGetJson)
if response.status_code == 200:
    data = json.loads(response.text)
    for record in data:
        print(record['envelope']['data']['message'])

For more information https://www.w3schools.com/python/ref_requests_response.asp

CodePudding user response:

Saeed already covered how to do this, but if you would like it in a nice Pandas DataFrame, you could do something like this:

data = json.load('file.json')
series = pd.Series(data) # Since it's an array, I'll turn that into a Series first
df = pd.json_normalize(series)

That DataFrame would automatically unnest inner json objects and represent them with column names like envelope.source and envelope.data.message.

Edit: Also if you did want this to read the json from requests, just use json.loads(data.json())

  • Related