-3

I'm searching for a way to read a specific value of multiple JSON arrays.

I was able to count them and now want to get a specific value from each of them but I wasn't able to find a way to set [0], [1], [2], etc. as a variable.

LineCount = len(obj['data']['monitors']);

print ("Active Lines:", LineCount)

LineNb = "obj['data']['monitors'][" + LineCount + "]['lines'][0]['name']"

LineName = json.dumps(LineNb)
        
print (LineCount, "Line", LineName)

while LineCount > 1:
    LineCount -= 1
    LineNb = "obj['data']['monitors'][" + LineCount + "]['lines'][0]['name']"
    print (LineCount, "Line", LineName)
4
  • A Json string is not a database where you can access arbitrary elements. If you want ho save selected elements then select them in Python and then dumps them to a string. Or use a nonSQL database that works on Json structures. Commented Oct 27, 2024 at 22:55
  • Don't put it in a string. Just use LineName = obj['data']['monitors'][LineCount]['lines'][0]['name'] Commented Oct 27, 2024 at 22:58
  • Yeah, the way you're doing it is incorrect. Rather than trying to access a string, use a JSON object as suggested. Putting it in a string has no purpose here, unless you're doing something like eval, which again begs the question - why? Commented Oct 27, 2024 at 23:24
  • If you want to iterate over the items in obj['data']['monitors'], then ... just do that. What is the difficulty? Commented Oct 27, 2024 at 23:30

1 Answer 1

0

Though not recommended, a quick fix is to eval the string:

LineNb = "obj['data']['monitors'][" + LineCount + "]['lines'][0]['name']"
LineNb = eval(LineNb)

...

Alternatively, I recommend just removing the quotes, to turn it from str into accessing the JSON object obj directly:


LineNb = obj['data']['monitors'][LineCount]['lines'][0]['name']

...
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.