I
I
ItzGuyMc2022-01-22 23:30:10
Python
ItzGuyMc, 2022-01-22 23:30:10

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

And so, with the help

[item for item in data['data']['list'] if item['user']['name'] == 'name1']
I filter the code and leave only the code where name == name1 (which is clear from the code), how can I return this code back to JSON and filter it again?
I tried using json.dumps() and json.loads(), it doesn't help - when I try to filter the code again I get an error
TypeError: list indices must be integers or slices, not str
using code like this:
[item for item in njson['data']['list'] if 'text' in item['message']]
tell me what to do

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
o5a, 2022-01-23
@o5a

It is logical that if

njson = [item for item in data['data']['list'] if item['user']['name'] == 'name1']

then njson will be a list, not a nested dictionary. And accessing its elements as njson['data']['list'] doesn't make sense.
If the goal was to filter that list inside the original json, then it had to be changed:
data['data']['list'] = [item for item in data['data']['list'] if item['user']['name'] == 'name1']

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question