This might help you.
def func1(data):
for key,value in data.items():
print (str(key)+'->'+str(value))
if type(value) == type(dict()):
func1(value)
elif type(value) == type(list()):
for val in value:
if type(val) == type(str()):
pass
elif type(val) == type(list()):
pass
else:
func1(val)
func1(data)
All you have to do is to pass the JSON Object as Dictionary to the Function.
There is also this python library that might help you with this.You can find this here -> JsonJ
Answer from Joish on Stack OverflowPEACE BRO!!!
This might help you.
def func1(data):
for key,value in data.items():
print (str(key)+'->'+str(value))
if type(value) == type(dict()):
func1(value)
elif type(value) == type(list()):
for val in value:
if type(val) == type(str()):
pass
elif type(val) == type(list()):
pass
else:
func1(val)
func1(data)
All you have to do is to pass the JSON Object as Dictionary to the Function.
There is also this python library that might help you with this.You can find this here -> JsonJ
PEACE BRO!!!
I found the solution on another forum and wanted to share with everyone here in case this comes up again for someone.
import csv
import json
path = 'E:/Thesis/thesis_get_data'
with open (path + "/" + 'maplightdata110congress.json',"r") as f:
data = json.load(f)
for bill in data['bills']:
for organization in bill['organizations']:
print (organization.get('name'))`
python - Iterate through nested JSON object - Stack Overflow
How to Iterate through nested JSON in Python - Stack Overflow
Iterating nested json in python - Stack Overflow
python - iterate through nested JSON - Stack Overflow
My Json is of the following format:
https://pastebin.com/KUKHHh2e
The numbers in this json are many as are the dates. I am trying to iterate through this to create a single list of dictionaries that contains all of the information in the dictionary that is 3 layers deep in the json.
I have made a loop that is n3 but it seems highly inefficient given i have around 30,000 iterations to make.
What are my options here?
Loop through countries['Europe'].items():
countries = {"Europe":
{"Germany": [{"hostname": "host1"}],
"Poland": [{"hostname": "host2"}],
"Denmark": [{"hostname": "host3"}]}
}
for k, v in countries["Europe"].items():
print(k, v[0]['hostname'])
Germany host1
Poland host2
Denmark host3
>>>
Try with json to load as dictionary:
import json
contries = """
{
"Europe": {
"Germany": [
{
"hostname": "host1"
}
],
"Poland": [
{
"hostname": "host2"
}
],
"Denmark": [
{
"hostname": "host3"
}
]
}
}
"""
country_host = json.loads(contries)
for k,v in country_host['Europe'].items():
print(k,v[0]['hostname'])
this will print out countries and its host:
Denmark host3
Germany host1
Poland host2
json_res['nodes'] is a dictionary. Iterating over a dictionary just gives you the keys, so the first value of node could be, for example, 'Server1'. If you want both the keys and values you can iterate using .items():
for key, node in json_res['nodes'].items():
If you only want the values of the nodes, you can use .values():
for node in json_res['nodes'].values():
You are missing a level of deepness of your data since json_res['nodes'] is a dictionary
json_res['nodes'] = {
"Server1": {
"status": "running",
...
You can add a nested loop to print servers status:
for node in json_res['nodes']:
for server in node:
print server['status']
results['playlists']['items'][0]['owner']['id']
^___ this is a list index
Thus:
for item in results['playlists']['items']:
print(item['owner']['id'])
It is often convenient to make intermediate variables in order to keep things more readable.
playlist_items = results['playlists']['items']
for item in playlist_items:
owner = item['owner']
print(owner['id'])
This is assuming I have correctly guessed the structure of your object based on only what you have shown. Hopefully, though, these examples give you some better ways of thinking about splitting up complex structures into meaningful chunks.
How about this? You can use generator to achieve your goal
def get_playlist_owner_ids(query):
results = sp.search(q=query, type='playlist')
for item in results['playlists']['items']:
yield item['owner']['id']
Here's the updated code with minimal changes, and it also fixes the issue while writing the JSONL file. The code in question would append a list of JSON to the file, which will make the file messier and hard to read through code.
import datetime
import json
ruletree = {
"contract": "1234",
"domainName": "www.domainA.com",
"rules": {
"name": "default",
"children": [
{
"rule": "Rule1",
"children": [],
"behaviors": [
{
"name": "origin",
"options": {
"originType": "CUSTOMER",
"host": "gateway1.com",
},
}
],
},
{
"rule": "Rule2",
"children": [],
"behaviors": [
{
"name": "origin",
"options": {
"originType": "CUSTOMER",
"host": "gateway2.com",
},
}
],
},
],
},
}
data = {
'date_time': datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M:%S"),
'domainName': ruletree['domainName'],
}
#code to get domainName, name & host
for rule in ruletree['rules']['children']:
for behavior in rule['behaviors']:
with open('domains.json', 'a+') as outfile: # writing to the file
json.dump({
**data,
'rule': rule['rule'],
'host': behavior['options']['host']
}, outfile)
outfile.write('\n')
File output:
{"date_time": "2023-07-11 11:28:21", "domainName": "www.domainA.com", "rule": "Rule1", "host": "gateway1.com"}
{"date_time": "2023-07-11 11:28:21", "domainName": "www.domainA.com", "rule": "Rule2", "host": "gateway2.com"}
A simple generator function will do here.
def get_rule_data(ruletree):
for child in ruletree["rules"]["children"]:
rule_name = child["rule"]
for behavior in child.get("behaviors", []):
try:
host = behavior["options"]["host"]
yield ruletree["domainName"], rule_name, host
except KeyError:
pass
now = datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
for domain, rule_name, origin_domain in get_rule_data(ruletree):
print(
{
"date_time": now,
"domainName": domain,
"rule_name": rule_name,
"host": origin_domain,
}
)
Try:
def get_kv(o):
if isinstance(o, dict):
if "path" in o and "url" in o:
yield o["path"], o["url"]
for v in o.values():
yield from get_kv(v)
elif isinstance(o, list):
for v in o:
yield from get_kv(v)
print(dict(get_kv(data)))
Prints:
{
"/1": "1_URL",
"/12": "12_URL",
"/123": "123_URL",
"/13": "13_URL",
"/131": "131_URL",
"/1311": "1311_URL",
"/13111": "13111_URL",
}
OK ... there is an excellent answer there by Andrej Kesely, so let's apply this answer to your json_extract function:
def json_extract(json_dct, key1, key2):
dct = {}
def extract(json_dct, key1, key2):
if isinstance(json_dct, dict):
if key1 in json_dct and key2 in json_dct:
dct[json_dct[key1]] = json_dct[key2]
for v in json_dct.values():
extract(v, key1, key2)
elif isinstance(json_dct, list):
for v in json_dct:
extract(v, key1, key2)
return dct
result = extract(json_dct, key1, key2)
return result
print(json_extract(data, "path", "url",))
And if you are curios how your way of approaching it could be turned into what you intended it to be without using the revelation that you have here to do with a dictionary from which all keys are available in parallel, check out:
def json_extract(obj, key, key2):
stack = []
dct = {}
def extract(obj, dct, stack, key, key2):
if isinstance(obj, dict):
for k, v in obj.items():
if k == key2:
stack.append(v)
if isinstance(v, (dict, list)):
extract(v, dct, stack, key, key2)
elif k == key:
dct[stack.pop()] = v
elif isinstance(obj, list):
for item in obj:
extract(item, dct, stack, key, key2)
return dct
result = extract(obj, dct, stack, key, key2)
return result
Hi there, I am trying to read through a package.json file which is below. I want to read in specifically the dependencies and add them to key, value variables. I can't figure out how to read in nested object. If anyone can give me any tips?
{
"name": "untitled",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "5.0.0",
"express": "https://github.com/IAmAndyIE/expressjs.com.git"
},
}My current code is below.
import json
def test_document():
f = open('../untitled/package.json')
data = json.load(f)
for key, values in data.items():
if key == "dependencies":
print(values)
f.close()
if __name__ == '__main__':
test_document()Thanks