How to get the value by a key from a super nested Json
You could take a recursive approach and return if a value is found.
function getValue(object, key) { var value;
if (!object || typeof object !== 'object') return; if (key in object) return object[key];
Object.values(object).some(v => { value = getValue(v, key) return value !== undefined; });
return value;}
var data = { _embedded: { "cscaia:status_report": { _links: { self: { title: "status_report", name: "status_report", href: "https://api.dxc-dev-aia.hub-1.dev.us.insurance.dxc.com/quotes/ID-mrMxY1Dg/status_report" }, type: { href: "https://diaas-dev.gtaia-test-domain.net/std-dev-lux-13100/insurance/schemas/quotes/statusReportDocument" }, up: { href: "https://api.dxc-dev-aia.hub-1.dev.us.insurance.dxc.com/quotes/ID-mrMxY1Dg" } }, consistent: false, messages: [{ message: "Incomplete attribute", context: [{ propertyNames: ["quote$distributor_id"] }], severity: "error", code: "incomplete_attr" }] } } };
console.log(getValue(data, 'severity'));console.log(getValue(data, 'href'));
Python extract only 'key' values in in nested JSON where 'value' is a dictionary in a list
Assuming your global dictionary has been loaded in data
you can extract the keys with a comprehension:
keys = [k for val in data.values() for d in val for k in d.keys()
if k != 'recordsCount']
And you can easily write them into a csv file with:
with open('file.csv', 'w', newline='') as fdout:
wr = csv.writer(fdout)
wr.writerow(keys)
Javascript get key of nested JSON object?
You can try this. This will give you only the expiration dates
.
var obj = {
"options": [{
"10-2-2001": "",
"someOtherProp": ""
}, {
"20-2-2001": "",
"someOtherProp": ""
}]
}
var expDates = obj.options.map(o=>Object.keys(o)[0])
console.log(expDates)
How to access nested JSON object key and values
Something like that?
You have to firstly acces to object.types attribute, then iterate on it to retrieve every type.
var object = { "nodes": [{ "nd": "nd1", "cat": "cat1" }], "links": [{ "id": 100 }], "types": [{ "type": "one", "image": "image001" }, { "type": "two", "image": "image002" }, { "type": "three", "image": "image003" }]};
function parseJson(object){ object.types.forEach(function(key) { console.log(key.type); });}
parseJson(object);
How to return specific key value pair from nested json without knowing location?
The underlying question is: how can we make multiple recursive calls in a loop, return
the recursive result if any of them returns something useful, and fail otherwise?
If we blindly return
inside the loop, then only one recursive call can be made. Whatever it returns, gets returned at this level. If it didn't find the useful result, we don't get a useful result.
If we blindly don't return inside the loop, then the values that were returned don't matter. Nothing in the current call makes use of them, so we will finish looping, make all the recursive calls, reach the end of the function... and thus implicitly return None
.
The way around this, of course, is to check whether the recursive call returned something useful. If it did, we can return that; otherwise, we keep going. If we reach the end, then we signal that we couldn't find anything useful - that way, if we are being recursively called, the caller can do the right thing.
Assuming that None
cannot be a "useful" value, we can naturally use that as the signal. We don't even have to return it explicitly at the end.
After fixing some other typos (we should not overwrite the global built-in dict
name, and anyway we don't need to name the dict that we pass in at the start, and the parameter should be m_dict
so that it's properly defined when we make the recursive call), we get:
def recursive_json(data, attr, m_dict):
for k,v in data.items():
if k == attr:
for k2,v2 in v.items():
m_dict = {attr, v2}
print('IF: ', m_dict)
return m_dict
elif isinstance(v,dict):
result = recursive_json(v, attr, m_dict)
if result:
return result
# call it:
recursive_json(json_data, "Date", {})
We can see that the debug trace is printed, and the value is also returned.
Let's improve this a bit:
First off, the inner for k2,v2 in v.items():
loop doesn't make any sense. Again, we can only return
once per call, so this would skip any values in the dict after the first. We would be better served just returning v
directly. Also, the m_dict
parameter doesn't actually help implement the logic; we don't modify it between calls. It doesn't make sense to use a set
for our return value, since it's fundamentally unordered; we care about the order here. Finally, we don't need the debug trace any more. That gives us:
def recursive_json(data, attr):
for k, v in data.items():
if k == attr:
return attr, v
elif isinstance(v,dict):
result = recursive_json(v, attr)
if result:
return result
To get fancier, we can separate the base case from the recursive case, and use more elegant tools for each. To check if any of the keys matches, we can simply check with the in
operator. To recurse and return the first fruitful result, the built-in next
is useful. We get:
def recursive_json(data, attr):
if not isinstance(data, dict):
# reached a leaf, can't search in here.
return None
if attr in data:
return k, data[k]
candidates = (recursive_json(v, attr) for v in data.values())
try:
# the first non-None candidate, if any.
return next(c for c in candidates if c is not None)
except StopIteration:
return None # all candidates were None.
Related Topics
Pause/Stop Videos into Tabs When I Clicked on a Tab
React Router - Stay At the Same Page After Refresh
How to Format Base64 Encoded String While Sending in Json
How to Disable Print-Screen Functionality for a Webpage in All Browsers
How to Include External JavaScript Library in Reactjs
How to Apply the Length Condition on the Existing Regular Expression
How to Load All the Images from One of My Folder into My Web Page, Using Jquery/Javascript
How to Import File from Public Folder in React Application
Converting String Date in React/Javascript
Javascript: Replace Last Occurrence of Text in a String
Dynamically Add Variable Name Value Pairs to Json Object
Check If a Number Has a Decimal Place/Is a Whole Number
How to Remove the Div That a Button Is Contained in When the Button Is Clicked
How to Force Update Child Component from Parent Component in Reactjs
How to Access External Json File Objects in Vue.Js App
React Router Not Working After the Page Refresh
How to Select All Textframes in Document, and Retrieve the Text in Adobe Indesign