How to Extract Data from Json Nested Objects

How to extract nested JSON data?

Is this the full output? This a dictionary containing a list with nested dictionaries, so you should treat it that way. Suppose it is called:

A = {
"Tags": [
{
"Key": "Name",
"Value": "Trove-Dev-Inst : App WebServer"
},
{
"Key": "aws:autoscaling:groupName",
"Value": "CodeDeploy_Ernie-dev-Autoscaling-Deploy_d-4WTRTRTRT"
},
{
"Key": "CodeDeployProvisioningDeploymentId",
"Value": "d-4WTRTRTRT"
},
{
"Key": "Environment",
"Value": "ernie-dev"
}
]
}

Your first adress the object, then its key in the dictionary, the index within the list and the key for that dictionary:

print(A['Tags'][1]['Value'])

Output:

CodeDeploy_Ernie-dev-Autoscaling-Deploy_d-4WTRTRTRT

EDIT: Based on what you are getting then you should try:

autoscaling_name = response['Reservations'][0]['Instances'][0]['Tags'][1]['Value']

Extract values from nested JSON to array using JS

You can write a recursive function which returns the text value at the current node, then all the text values from its child items:

const data = [{"itemID":"1","items":[{"itemID":"2","items":[{"itemID":"3","items":[{"itemID":"15","text":"Ryzen"},{"itemID":"16","text":"Threadripper"}],"text":"AMD"},{"itemID":"66","items":[{"itemID":"76","text":"i5"},{"itemID":"77","text":"i7"},{"itemID":"78","text":"i3"}],"text":"Intel"},{"itemID":"70","text":"Apple"}],"text":"CPUs"}],"text":"computer parts"},{"itemID":"4","items":[{"itemID":"5","items":[{"itemID":"21","text":"porsche"},{"itemID":"22","text":"maserati"},{"itemID":"23","text":"ferrari"}],"text":"sports cars"}],"text":"cars"}];

const extract = (arr) => arr.reduce((acc, obj) => acc.concat(obj.text, extract(obj.items || [])), [])

out = extract(data);
console.log(out);

Extract value inside a multi-nested JSON Object with a "number" as a key name?

you can use the obj[key] syntax

top100['content'][1]['title']

Rails how to extract data from nested JSON data

I needed to convert your example into json. Then I could loop the quotas and output the values.

hash = JSON::parse(data.to_json)
hash['quotas'].each do |data|
p data["responders"]
data["qualified"].each do |responder|
p responder['service_id']
p responder['codes']
end
end

Hash in data variable (needed for the sample code to work):

require "json"

data = {
"id": 14706,
"relationships": [
{
"id": 538
}
],
"quotas": [
{
"id": 48894,
"name": "Test",
"responders": 6,
"qualified": [
{
"service_id": 12,
"codes": [
1,
2,
3,
6,
]
},
{
"service_id": 23,
"pre_codes": [
1,
2
]
}
]
}
]
}

Extract nested JSON data with Python pandas

Convert your json string to a python data structure using json.loads and then use json_normalize:

import json

cols = ['time', 'close', 'high', 'low']
data = json.loads(res)
df = pd.json_normalize(data['Data'], record_path='Data')[cols]
df = df.astype({'time': 'datetime64[s]'}).set_index('time')

Output:

>>> df
close high low
time
2021-08-26 46852.22 49358.20 46456.68
2021-08-27 49088.10 49166.31 46376.81

How to extract both deeply and shallowly nested fields in array of json objects

You could create recursive function for this using for...in loop and only add to the result when the current object have no elements in the children array.

const data = [{"value":"someName","property":"name","children":[],"constraints":{"IsValidName":"name someName isn't valid"}},{"value":[{"id":"firstBadId"},{"id":"secondBadId"}],"property":"listOfIds","children":[{"value":{"id":"firstBadId"},"property":"0","children":[{"value":"firstBadId","property":"id","children":[],"constraints":{"badIdError":"This Id is bad!"}}]},{"value":{"id":"secondBadId"},"property":"1","children":[{"value":"secondBadId","property":"id","children":[],"constraints":{"badIdError":"This Id is bad"}}]}]}]
function extract(data, fields) { let result = []
for (let i in data) { if (typeof data[i] == 'object') { result.push(...extract(data[i], fields)) }
if (data.children && !data.children.length) { if (fields.includes(i)) { result = result.concat( typeof data[i] == 'object' ? Object.values(data[i]) : data[i] ) } } }
return result;}
const result = extract(data, ['property', 'value', 'constraints'])console.log(result)

How to extract data from nested json array?

You can get the arrays as an array of arrays with Object.values. How you go from there depends on what specifically you're after. To get your output as strings, you can map() over the outer array and join() everything:

let j = {     question_xx: [ 'Another question?', 'Probably yes' ],    question_3: [ 'Home origin planet?', 'Mars' ],     question_2: [ 'Are you from planet Earth?',   'No' ],      question_1: [ 'Home origin Galaxy?', 'Milky Way' ],   }
// array of arrayslet arr = Object.values(j)console.log(arr)
// join arrays as strings// join inner arrays with space, outer arrays with new linelet strings = arr.map(arr => arr.join(" ")).join(' \n')console.log(strings)

How to extract objects from nested lists from a Json file with Python?

Since the data that you specified is nested pretty deeply in the JSON-response, you have to loop through it and save it to a list temporarily. To understand the response data better, I would advice you to use some tool to look into the JSON structure, like this online JSON-Viewer. Not every entry in the JSON contains the necessary data, therefore I try to catch the error through a try and except. To make sure that the id and committees are matched correctly, I chose to add them as small dicts to the list. This list can then be read into Pandas with ease. Saving to .dta requires you to convert the lists inside the committees column to strings, instead you might also want to save as .csv for a more generally usable format.

import requests, json
import pandas as pd


query = {"naics": "424430"}
results = requests.post(
"https://www.lobbyview.org/public/api/reports", data=json.dumps(query)
)


json_response = results.json()["result"]

# to save the JSON response
# with open("data.json", "w") as outfile:
# json.dump(results.json()["result"], outfile)

resulting_data = []

# loop through the response
for data in json_response:
# try to find entries with specific issues, bills_by_algo and committees
try:
# loop through the special issues
for special_issue in data["specific_issues"]:
_id = special_issue["id"]
# loop through the bills_by_algo's
for x in special_issue["bills_by_algo"]:
# append the id and committees in a dict
resulting_data.append(({"id": _id, "committees": x["committees"]}))

except KeyError as e:
print(e, "not found in entry.")
continue


# create a DataFrame
df = pd.DataFrame(resulting_data)
# export of list objects in the column is not supported by .dta, therefore we convert
# to strings with ";" as delimiter
df["committees"] = ["; ".join(map(str, l)) for l in df["committees"]]
print(df)
df.to_stata("result.dta")


Results in

                         id                                         committees
0 D8BxG5664FFb8AVc6KTphJ House Judiciary
1 D8BxG5664FFb8AVc6KTphJ Senate Judiciary
2 8XQE5wu3mU7qvVPDpUWaGP House Agriculture
3 8XQE5wu3mU7qvVPDpUWaGP Senate Agriculture, Nutrition, and Forestry
4 kzZRLAHdMK4YCUQtQAdCPY House Agriculture
.. ... ...
406 ZxXooeLGVAKec9W2i32hL5 House Agriculture
407 ZxXooeLGVAKec9W2i32hL5 Senate Agriculture, Nutrition, and Forestry; H...
408 ZxXooeLGVAKec9W2i32hL5 House Appropriations; Senate Appropriations
409 ahmmafKLfRP8wZay9o8GRf House Agriculture
410 ahmmafKLfRP8wZay9o8GRf Senate Agriculture, Nutrition, and Forestry

[411 rows x 2 columns]

How to extract data from nested json in react

nastavnik variable is a string. You should convert it to object by: JSON.parse(str)
For example: