I am somewhat a beginner in python and I am trying to search for a specific keyword in a Json file. I have been reading up on how dictionaries and lists work in python and I came across this:
complex_list = [["a",["b",["c","x"]]],42]
complex_list[0][1]
output: ['b', ['c', 'x']]
complex_list[0][1][1][0]
output: 'c'
As I understand, in complex_list[0][1]
, the [0]
is the entire bracket [
, ]
, and [1]
accesses the second part of the bracket: [, [this one] ]
.
Now, this one: complex_list = [["a",["b",["c","x"]]],42]
, has 2 elements within the list correct? a, b, c ,and x belong to one set and 42 belongs to the second set. I don't know how to interpret this: complex_list[0][1][1][0]
to access 'c'
.
Could someone break it down please? I ask this because I think this is what I need to use to solve the problem I explain below.
This is a small sample from the file I am working with at the moment:
{ (white)
"results": [
{ (black)
"Fruit": "Apple",
"Nested fruit": [
"Orange"
],
"Title1": "Some text",
"Contents": { (yellow)
"Name 1": [
"John Smith"
],
"Name 2": [
"Tyler"
],
"Name 3": [
"Bob",
"Rob"
],
"Name 4": [
"Linda"
],
"Name 5": [
"Mark",
"Matt"
],
"Some boolean": [
true
]
}, (yellow)
"More stuff": "More random text",
"Confusing": [
{ (red)
"Some info": "456",
"Info I want": "849456"
} (red)
],
"Not important": [
{ (blue)
"random text": "bla",
"random text2": "bla bla"
} (blue)
],
"Not important 2": "000",
"Not important3": [
"whatever",
"whatever"
],
"Not important 4": "16",
"Not important 5": "0058"
} (black)
]
} (white)
I have put colors in parenthesis next to their corresponding curly braces so that it is easy to distinguish. Following some examples online, I found:
import json
with open('searchingKeywords.json') as f:
data = json.load(f)
print(data.keys())
for k in data:
for v in data[k]:
if 'More stuff' in v:
print("yes")
which prints:
dict_keys(['results'])
yes
There is only 1 key, but what about Contents? Isn't that another key within results? I am so confused. What I am interested in is "info I want" inside "Confusing". How do I search inside so many nested things if keyword "Info I want" is contained? Initially, I tried reading line by line-- once I parsed the Json file into a Python object-- and then see if a keyword "Info I want" is found in each line but I kept getting errors. Additionally, the file I am working with is huge and "Info I want" may be nested differently.