Fletchy
Fletchy

Reputation: 351

Error accessing specific value from JSON file

I'm trying to parse some JSON, and I need to extract certain values and store them in a 2D list. However when I try to save a single value I keep getting an TypeError. Also I am using Python 3.6.8.

I have tried to look at a couple different solutions, like casting it as a list, integer and string. I also have looked at the following links: attempt1 , attempt2 and attempt3. I believe the error is coming from how I am attempting to access the value. I have tried to play around with my code to get it to run properly but I just cannot get it to execute.

This is my code:

with open('../data.json') as json_data:
    j = json.load(json_data)
    json_data.close()

for chat in range(len(j["data"]["chats"])):
    temp = []
    for msg in range(len(j["data"]["chats"][chat]["messages"])):
        item = j[["data"]["chats"][chat]["messages"][msg]["sender"]["id"]]
        print(item)

This is some of my JSON:

{  
    "application":"HelloWorld",
    "data":{  
       "chats":[  
          {  
             "name":"max",
             "parties":[  
                {  
                   "id":"1"
                },
                {  
                   "id":"2"
                }
             ],
             "messages":[  
                {  
                   "sender":{  
                      "id":"1"
                   },
                   "id":"1234",
                   "content":[  
                      {  
                         "data":"Hello number 2",
                         "type":"txt"
                      }
                   ],
                   "timestamp":{  
                      "created":816080400
                   }
                },

The chat section repeats 4 times, the message item repeats a couple times in each chat, and then the sender item repeats a couple times in each message item.

Currently my code just shoots out an error at the line:

item = j[["data"]["chats"][chat]["messages"][msg]["sender"]["id"]]

The Error is:

Traceback (most recent call last):
  File "main.py", line 14, in <module>
    item = j[["data"]["chats"][chat]["messages"][msg]["sender"]["id"]]
TypeError: list indices must be integers or slices, not str

What I would like to do is successfully print the value so the following happens:

print(item)
#Will print:1

Upvotes: 1

Views: 48

Answers (1)

amarynets
amarynets

Reputation: 1815

I don't know why do you use len() for iteration if it is not required this code will give you what you want, where app variable is your json

for chat in app['data']['chats']:
    for msg in chat['messages']:
        item = msg['sender']['id']
        print(item)

UPD1: Your version looks like that:

j[["data"]["chats"][chat]["messages"][msg]["sender"]["id"]]
j["data"]["chats"][chat]['messages'][msg]['sender']['id']

As you can see - there is [] near j variable

Upvotes: 1

Related Questions