D3 get the value in the middle of nested JSON - json

Totally noob question from me. Different from other JSON nested questions, I want to access the value of the middle level.
Consider that I have a JSON like:
"nodes":[
{"Level1":[
{"Level2A":[
{"Level3A":"Value",
"Level3B":"Value"
},
{"Level3A":"Value",
"Level3B":"Value"
}]
},
{"Level2B":[
{"Level3A":"Value",
"Level3B":"Value"
},
{"Level3A":"Value",
"Level3B":"Value"
}]
}]
}]
I want to get the value of Level2 out(to use as label).
I can get lv3 value by calling for example,:
node.datum().Level1[0].Level2[0].Level3A
but if I tried
nodae.datum().Level1[].Level2
I get an object instead. The ideal output would be the array with [Level2A, Level2B,...]

Are you sure your json is in valid mode or you just post half of it?
That what I did-
{"nodes":[{"Level1":[{"Level2A":[{"Level3A":"Value","Level3B":"Value"},{"Level3A":"Value", "Level3B":"Value"}],"Level2B":[{"Level3A":"Value","Level3B":"Value"}]}]}]}

Related

Is it possible to get a sorted list of attribute values from a JSON array using JSONPath

Given JSON like:
[
{
"Serial no": 994,
},
{
"Serial no": 456,
}
]
I know this query will give me an array of all Serial no values, in the order they are in the JSON: $..['Serial no']
I'm not sure exactly what sorting capabilities JSONPath has but I think you can use / and \ to sort - but how are they used to modify my query string in this case? I am only interested doing this in pure JSONPath, not JS or post-query sorting - that's easy, I just want to know if I can avoid it.
This is a source I found suggesting sorting is supported but it might be product-specific?
I'm using http://www.jsonquerytool.com/ to test this

JSONPath get the id of a parent element by a sub-child value

Given the following JSON I want to get the id field of the parent by an equals text compare of a sub-child element:
{
"datapoints": [{
"id": "default.1",
"definedBy": "default/0.1",
"featureValues": {
"bui.displayname": "Health status",
"bui.visibility": "normal",
"default.access": "r",
"default.basetype": "text",
"default.description": "Aggregated health status",
"default.format": "text/plain",
"default.name": "health_status",
"default.restriction": "re:(OK|WARN|ERROR|UNKNOWN)"
}
}, {
"id": "kdl.240",
"definedBy": "kdl/0.9",
"featureValues": {
"bui.displayname": "Delta K",
"bui.visibility": "normal",
"default.access": "rw",
"default.basetype": "real",
"default.description": "Delta K",
"default.name": "Delta_K",
"default.privacy": "false",
"default.restriction": "b32"
}
}
]
}
My first goal is to get the correct data point by a sub-child text compare like:
$['datapoints'][*]['featureValues'][?(#['default.name']=='Delta_K')]
It seems not to work when I test it on http://jsonpath.com/
To get all the data points I used this successfully:
$['datapoints'][*]['featureValues']['default.name']
My goal is to get the id value of the data point with the featureValues child element default.name is equal Delta_K. In the example this would be kdl.240.
I could only solve the first part of my question by using:
$['datapoints'][*][?(#['default.name']=='Delta_K')]
During my research I found that jsonpath does not support to get the parent of a filtered node. In Chapter 7 "Conclusion" of http://www.baeldung.com/guide-to-jayway-jsonpath it's written:
Although JsonPath has some drawbacks, such as a lack of operators for reaching parent or sibling nodes, it can be highly useful in a lot of scenarios.
Also further SO posts couldn't help me.
Getting parent of matched element with jsonpath
Using jsonpath to get parent node
The following code is working for me on https://jsonpath.com :
$.datapoints[?(#.featureValues['default.name']=='Delta_K')].id
You need to find a node containing a featureValues attribute that contains a default.name attribute that matches your text. Using the suggestion at the end of https://github.com/json-path/JsonPath/issues/287 you can get what you want with:
$..[?(#.featureValues[?(#['default.name']=='Delta_K')] empty false)].id
#cat jsonData.json | jq ‘.datapoints[].featureValues | select .default.name == 'Delta_K') | .id’
see also:
https://github.com/adriank/ObjectPath/issues/70

How to extract JSON values that does not have attribute names?

{
"A1":{
"name":"Ad hoc",
"projectId":0
},
"X2":{
"name":"BBB",
"projectId":101
},
"AB":{
"name":"CCC",
"projectId":102
},
"recordsCount":3
}
For this JSON, how to extract values? i need output like,
A1, Ad hoc
X2, BBB
AB, CCC
experts inputs appreciated.
Analysis
XPath can't read unnamed attributes. It will always result in an exception. If you want to get the values, you need to use JsonPath.
Solution
Even then, it makes sense to add surrounding brackets, otherwise the first level will be consumed as well:
[
{
"A1":{
"name":"Ad hoc",
"projectId":0
},
"X2":{
"name":"BBB",
"projectId":101
},
"AB":{
"name":"CCC",
"projectId":102
},
"recordsCount":3
}
]
You can try the correct query on jsonpath.com. For me (with the additional brackets) the path $.* worked.
To extract the values, you need to use a tExtractJSONFields component in Talend if using a file or REST request.
A valid JSON query could be easily [0] for the field with alphanumeric identifiers.

Getting and displaying JSON data fields using HTML and AngularJS

Im new to angularJS and web designing as a whole. Im trying to get a data field(or element) from a JSON. For example, this is what the JSON looks like
{
"Name":"Raymond Eugene Monce",
"Dateofbirth":"1924-0308T00:00:00Z",
"Ethnicity":"Caucasian",
"Languages":["{English}"],
},
and I'm trying to get the "Name" data field. This is what my .js file looks like,
var profile = angular.module('profile', ['ui.bootstrap','ngResource']);
profile.controller("profileController", ["$scope","$resource", function($scope, $resource) {
// get the user id
$scope.userid = sessionStorage["cerestiuserid"];
// json we get from server
$scope.apicall = sessionStorage["cerestihome"]; // NEED TO CHANGE API
// grabs the user we want
$scope.userResource = $resource($scope.apicall + "/api/userprofile/",
{Userid:21},
{'get':{method: 'POST'}}
);
// fetch JSON
$scope.userResource.get(function(result) {
// get the name field
$scope.name = result;
sessionStorage["name"] = JSON.stringify(result);
});
and my .html file,
<div ng-controller = "profileController" style="float:left">
<!-- profile pic -->
<div class="pull-left">
<div class="container-fluid">
<div class="profile">
<div class="row">
<div class="center-block">
<div class="profilePic">
<img ng-src="{{profilePic()}}" class="img-responsive">
<!-- name field -->
<label class="caption">
<h4>{{name.name}}</h4>
</label>
</div>
Again, Im not having problems with the Database or API calls. I just want to know how I can get and display the name field of the JSON. Thanks.
strelok2010's comment above should work although that depends on if your result really looks like the one defined at the top of your question.
Your result seems to be a normal javascript object not JSON. (yeah they are different, and that confused me when I learned it.) I assume that because you stringify the result from a javascript object into JSON. Therefore if that is working right your result is either a javascript object or an array of javascript objects. I'm assuming an array. You might want to check though.
I noticed your earlier post had a related problem.
In that one you were asking to access a property of an object that was in an array. In that case it was result as well. Here was the answer from your previous question
var result = [{"name": "Jason"
"date of birth": "february 23, 2985"
....
}];
var firstResultsName = result[0].name;
There are two things I am unsure of due to the inconsistency between this and your last question.
First your name property in your results object is spelled with a capital N here as opposed to a lower case n in your last question.
Keep in mind that capitilization matters in javascript.
Second your result in your last question was an array of objects and in this it seems to be just an object.
So depending on which one it is will determine your solution. So instead of writing every possible solution I'll show you how to determine the solution.
Remember we are dealing with a normal array of javascript objects. I'll try to go into detail so it's extra clear (sorry I heard you were new to web developement, I'm assuming JavaScript too.), but sorry if it's a little too detailed. I will also be breaking it into parts to go deeper into the array of objects that I'll use in my example, but traversing into the data structure can all be done in a single line as I will show.
You can only do actions on the 'outermost-form' (by the way 'outermost-form' is just a term I'll use for clarification it's not really a technical term.) and work your way into the collection (object/array/string)
As an example we have an array of people, with the array being the 'outermost-form'
var people = [
{
"name": "Bob",
"occupation": "Architect",
"date of birth": "01/23/83"
},
{
"name": "Timothy",
"Occupation": "Accountant",
"date of birth": "02/23/78"
}
];
If we saw the value of people at this moment it not surprisingly be.
[
{
"name": "Bob",
"occupation": "Architect",
"date of birth": "01/23/83"
},
{
"name": "Timothy",
"Occupation": "Accountant",
"date of birth": "02/23/78"
}
]
Start with the Array
Since it's an array as the 'outermost-form' we can get one of its values using an index. Just like any other array. Just for a bit of contrast I'll show you how what we are doing is similar to any other array by showing an example of an array by itself
// simple array example
var array = ["foo", "bar", "baz"];
array[0] // returns "foo"
// more simple array example, but less practical (it's more just for showing how javascript can work.)
["foo", "bar", "baz"][2] // returns "baz"
Back to our main example. Let's make a variable person and store our first person in the people array in that value.
var person = people[0];
Now if saw our person variable it would equal the following
{
"name": "Bob",
"occupation": "Architect",
"date of birth": "01/23/83"
}
You can see just like the normal array it grabs the first item in the array. You can see how we are slowly traversing into our people data structure. (that being an array of objects.)
Enter the Object
Okay so now we have the person object, but we want the name of that person so since we are dealing with an object we have to access its properties we can do this with either 'dot notation', e.g. <object>.<property>, or 'bracket notation' which can be done with either a variable or a string for the property name. e.g. <object>.["<property>"] or <object>.[<variable>]
So just as a side example I will show you what it normally takes to get the value of a property of an object just so you can compare and see there's no 'magic' going on. Keep in mind javascript is case-sensitive. Also javascript objects properties can go with or without surrounding quotes unlike JSON. One last thing having a space in the property name forces us to use quotes, and also forces us to access that property via bracket notation.
var result;
var obj = { foo: 1, Bar: 2, "foo bar": 3 };
var randomVarName = "Bar"; // notice the capital B in Bar is important since it was declared that way.
result = obj.foo; // result equals 1
result = obj[randomVarName]; // result equals 2
result = obj["foo bar"]; // result equals 3
Back again to our main train of thought. So we have traversed into our people array to find the person object now let's get their name.
var name = person.name;
The value of name would be.
"Bob"
You can do with that what you wish. You could have also used any of the previous ways to get an objects property including bracket notation.
Do Everything we just did in a Single Line
So to write that all in one line you would just write
people[0].name
Apply to your Question
So to apply to your question if your result looks like this
var result = [
{
"name": "Jason"
"date of birth": "february 23, 2985"
....
}
];
Then you need this to get the name
result[0].name
If it's just this
var result = {
"name": "Jason"
"date of birth": "february 23, 2985"
....
}
Then you just need
result.name
As asked in the comment if you want to get the date of birth property out of the object you need to use bracket notation to get the element out of an object. Bracket notation is one of the two object property accessors the other being dot notation. I covered both at the enter the object section. It can be used at anytime, but is usable in some cases that dot notation does not work.
An example and quote from MDN:
get = object[property_name];
object[property_name] = set;
property_name is a string. The string does not have to be a valid identifier; > it can have any value, e.g. "1foo", "!bar!", or even " " (a space).
So since certain character like spaces can't be used in dot notation bracket notation must be used in those special cases when those characters are present.
Below is the bracket notation of the date of birth.
result["date of birth"]
Like I said before it can be used anywhere, but generally dot notation is preferred for its brevity. So just to show that, we will show the name field being accessed using bracket notation:
result["name"]
One additional reason you may want to use bracket notation is for its ability to use variables like so.
var prop_name = "date of birth";
result[prop_name];
which actually if you understand the principle of that example the MDN example might make more sense.
If you have a question feel free to leave me a comment.

Diplaying JSON multidimensional array

I have this JSON array, but I don't know how display it.
{
"grupy": [{
"id_grupa_parametrow": "1",
"id_grupa_nadrzedna": "0",
"nazwa_grupy": "1_1",
"opis_grupy": "hdghgh",
"kolejnosc": "1233"
}]
}
I tried:
result["grupy"].id_grupa_parametrow;
but it doesn't work.
You can use some online json editors to find your data easily. Anyway, you have an array defined for groupy index. So, use numerical indexes first:
result["grupy"][0].id_grupa_parametrow;
What you have to know is that {} means that it's an object and [] is an array. So result in an object which has grupy property - that's why you have to use a dot here - result.grupy.
grupy is an array to you should use [0] index - result.grupy[0].
And so on...
This is the right way in this case:
result.grupy[0].id_grupa_parametrow;
result.grupy[0].id_grupa_parametrow;