Python check json file with variables

2024/11/24 14:43:41

I have a json file which has 18 substrings like this: https://i.sstatic.net/aVWuw.png https://i.sstatic.net/RLlRX.png

But I have more json files who have different number of these substrings. So I did this to find how many there are in the text:

import jsonjson_str = open('jsonfile.txt', 'r').read()contact = json.loads(json_str)

So GraphImages_total is 18 . Every substring has comments --> data --> 0 --> owner --> username So I want to print the username.

comment_author = contact["GraphImages"][0]["comments"]["data"][0]["owner"]["username"]
print(comment_author)

This is for GraphImages_total = 0 But I want to do it for all of them.

So I need a way to make it like this:

for graph_image in contact['GraphImages']:comment_author = contact["GraphImages"][graph_image]["comments"]["data"][0]["owner"]["username"]print(comment_author)

But I get this error:

comment_author = contact["GraphImages"][graph_image]["comments"]["data"][0]["owner"]["username"]IndexError: list index out of range
Answer
contact["GraphImages"][0]["comments"]["data"][0]["owner"]["username"]^                      ^

This indicates where the lists of unknown length are. The GraphImages and data keys hold lists. To iterate over a list, you use a for .. in statement as follows:

my_list = ['foo', 'bar', 'baz']
for item in my_list:print(item)

Note that you're using item directly. item will in turn become 'foo', 'bar' and 'baz' on each respective iteration of the loop. You don't need to use any numeric indices nor count up any x or y.

Applied to your situation, you need two such loops:

for graph_image in contact['GraphImages']:for comment in graph_image['comments']['data']:print(comment['text'], comment['owner']['username'])
https://en.xdnf.cn/q/120520.html

Related Q&A

The Sum of Consecutive Numbers in Python

What I have to do is get the user input and add consecutive numbers starting with one using a loop until the sum equals or exceeds the input. Its an exercise, so Im trying to do this without using the …

how to write to a text file using python ?

I am trying to output a full for iteration. The output should be in a text file. How should I code for that ? The output should look like :Iteration 1 values --------> val1 < tab > val2 < …

Python: Sorting dictionary by key

I am trying to sort a dictionary by key.If I do the following, then the dictionary is sorted like this1, 20 10, 5 11, 3 2, 30 20, 2Instead, I wanted to sort it like the following:1, 20 2, 30 10, 5 11, …

Please see my problem, believe me it is easy to solve

i tried to implement async and await inside spawn child process. But it didnt worked. Please see this Expected output************* http://www.stevecostellolaw.com/************* http://www.stevecostello…

How to make discord bot ping users using discord.py [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 3 years ago.Improve…

how to edit hostname file using fabric

I have change my hosts file,so how to change hostname.my system is ubuntu. eg my hosts file:192.168.0.100 host1.mydomain.com 192.168.0.101 host2.mydomain.comI wanna the hostname file under /etc/hostnam…

functions and indentation in python [duplicate]

This question already has answers here:How do I get ("return") a result (output) from a function? How can I use the result later?(4 answers)Closed 3 days ago.Im taking a tutorial in udemy t…

How do I define a method to store a collection (e.g., dictionary)?

Im a beginner working on a library management system and theres something I cant get my head around. So I have a Books class that creates new book records. class Books:def __init__(self, title=None, au…

Python Regex punctuation recognition

I am stumped by this one. I am just learning regular expressions and cannot figure out why this will not return punctuation marks.here is a piece of the text file the regex is parsing:APRIL/NNP is/VBZ …

cant find brokenaxes module

I want to create a histogram with broken axes and found that there must be a module doing this called brokenaxes that works together with matplotlib (source) . Anyway, when I trie to import the modul…