Cannot access Childen of JSON - json

I need to be able to loop through each "item" from my JSON result. The JSON response looks like this. I would like to be able to access each specific id.
{
"prop1": {
"date": "2017-03-04 3:57:38 PM",
"item": [
{
"id": "37705",
"date": "2016-04-03",
"time": "1:30PM"
},
"location": "Location 1"
},
{
"id": "2000",
"date": "2016-05-03",
"time": "2:30PM"
},
"location": "Location 2"
},
]
}
}
This is what i have but i am getting "Cannot access Children"
using (WebResponse response = await request.GetResponseAsync())
{
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
var serializer = new JsonSerializer();
using (var jsonTextReader = new JsonTextReader(stream))
{
dynamic obj = serializer.Deserialize(jsonTextReader);
foreach (var item in obj)
{
foreach (var item2 in item["item"].Children())
{
Console.WriteLine(item2.id);
}
}
}
}
}

Related

Postman accessing child objects in Json in a Test

I am trying to access the name object in this Json to put in a local variable in a Postman Test.
Json
{
"Line": [
{
"Id": "1",
"LineNum": 1,
"Description": "Custom Design",
"Amount": 75.00,
"DetailType": "SalesItemLineDetail",
"SalesItemLineDetail": {
"ItemRef": {
"value": "4",
"name": "Design"
},
"UnitPrice": 75,
"Qty": 1,
"ItemAccountRef": {
"value": "82",
"name": "Design income"
},
"TaxCodeRef": {
"value": "NON"
}
}
}
]
}
I am using this code to loop through the Line Array but if I try and go deeper than 1 level Itemref it returns undefined
let ProductArray=[];
for (let i=0; i < Line.length; i++) {
//
ProductArray.push({
"value":Line[i].SalesItemLineDetail.ItemRef.name
})
}
I have also tried
'"value":Line[i].SalesItemLineDetail["ItemRef"].name
"value":Line[i].SalesItemLineDetail["ItemRef"]["name"]
all return ItemRef undefined
What is the correct syntax or code?
TIA
There are just some small pieces missing with your code. I re-create a test and mocked the same JSON data. I just add the missing pieces to your code and the test was Successful.
GET Request:
//Response body JSON
{
"Line": [
{
"Id": "1",
"LineNum": 1,
"Description": "Custom Design",
"Amount": 75,
"DetailType": "SalesItemLineDetail",
"SalesItemLineDetail": {
"ItemRef": {
"value": "4",
"name": "Design"
},
"UnitPrice": 75,
"Qty": 1,
"ItemAccountRef": {
"value": "82",
"name": "Design income"
},
"TaxCodeRef": {
"value": "NON"
}
}
}
]
}
// Tests
// Check response body
const res = pm.response.json().Line;
let ProductArray=[];
for (let i=0; i < res.length; i++) {
const res = pm.response.json().Line;
ProductArray.push({
"value":res[i].SalesItemLineDetail.ItemRef.name
})
// Lets see console.log result
console.log('Check For:', res[i].SalesItemLineDetail.ItemRef.name)
// Set Result to environment variables
pm.environment.set("variable_key", res[i].SalesItemLineDetail.ItemRef.name);
}
console.log output: Design which is also added to environment variables.

Get Values form Json, using jpath

{
"data": [
{
"id": "52fb62dc-a446-4fbb-9c7e-e75d8c90f6d9",
"name": "abx",
"address": {
"address1": "New Address 1",
"address2": "New Address 2",
"Pin":"800001"
}
},
{
"id": "52fb62dc-a446-4fbb-9c7e-e75d8c90f6d9",
"name": "xyz",
"address": {
"address1": "New Address 1",
"address2": "New Address 2",
"Pin":"800002"
}
},
{
"id": "52fb62dc-a446-4fbb-9c7e-e75d8c90f6d9",
"name": "ijk",
"address": {
"address1": "New Address 1",
"address2": "New Address 2",
"Pin":"800003"
}
}
]
}
Out put json should be like this
[
{
"name": "abx",
"Pin": "800001"
},
{
"name": "xyz",
"Pin": "800002"
},
{
"name": "ijk",
"Pin": "800003"
}
]
From the input json, I want to extract all values using
jpath
Name Path = "data.name"
Pin Path = "data.address.pin"
I need all values, I will create an output json.
If both json and jpath are dynamic then try using the below code, here i have used the same input json and output json in my code block.
$(document).ready(function () {
var outputArr = [];
//Assume that these jpaths are dynamic.
var name = "data.name", pin = "data.address.Pin";
//Assigned input json object to sampleData variable.
$.each(sampleData.data, function (item, value) {
//Replacing 'data.' with empty('') as we are looping through data array.
var nameValue = extractValue(value, name.replace('data.', ''));
var pinValue = extractValue(value, pin.replace('data.', ''));
outputArr.push({ 'name': nameValue, 'Pin': pinValue });
});
//logging into console for testing purpose.
console.log(outputArr);
--to do with outputArr --
//Recursive function that returns the required value from the json
function extractValue(value, jPathKey) {
if (jPathKey.split(".").length > 1) {
//Here use of replace function is must as we need to get the object with the mentioned jPathKey to loop further.
return extractValue(value[jPathKey.replace('.', '$').split('$')[0]], jPathKey.replace('.', '$').split('$')[1])
}
else {
return value[jPathKey];
}
}
});
Note: Here only thing that need to take care is the case of jpath should match with case of input json

Mapping data that contains dots in React

I am trying to map the data in React that is coming from the API but I am having problems mapping the object that contains dots for example this: name.en_US.
What is the proper way to map this object and keeping the data structure that I have?
I am getting the date in this format from the API:
{
"user": "User",
"employeeId": "0000",
"businessCustomer": "customer",
"endCustomer": {
"name": "",
"address": "",
"place": ""
},
"device": {
"shipmentIds": "23",
"name.en_US": "wasi",
"name.fi_FI": " masi"
},
"task": {
"time": "2019-02-10T16:55:46.188Z",
"duration": "00:00:24",
"sum": "75€"
}
},
And then I am trying to map it using the following code.
const {
user,
employeeId,
businessCustomer,
endCustomer,
device,
task
} = task;
const{
endCustomerName,
address,
place
} = endCustomer;
const {
shipmentIds,
names
} = device;
const{
en_US,
fi_FI
} = names;
const {
time,
duration,
summa
} = task;
const data = {
"user": "User",
"employeeId": "0000",
"businessCustomer": "customer",
"endCustomer": {
"name": "",
"address": "",
"place": ""
},
"device": {
"shipmentIds": "23",
"name.en_US": "wasi",
"name.fi_FI": " masi"
},
"task": {
"time": "2019-02-10T16:55:46.188Z",
"duration": "00:00:24",
"sum": "75€"
}
};
const { device } = data;
const {
shipmentIds,
'name.en_US': name_en_US,
'name.fi_FI': name_fi_FI
} = device;
const nameUS = device['name.en_US'];
console.log(name_en_US, nameUS);
Use [ ] notation like, device['name.en_US'] .
You can destructure your propery as #Vishnu mentioned, or you could also destructure it by providing a valid key name
const {
shipmentIds,
'name.en_US': name_en_US,
'name.fi_FI': name_fi_FI
} = device;
And then you could access your variable with name_en_US.

Access nested JSON object in AngularJS controller

I am new to AngularJS and trying to create a $scope for tracks for later usage
data.json (sample):
[
{
"album": "Album name",
"tracks": [
{
"id": "1",
"title": "songtitle1",
"lyric": "lyrics1"
},
{
"id": "2",
"title": "songtitle2",
"lyric": "lyrics2"
}
]
}
]
Controller
app.controller('lyricsCtrl', function($scope, $http) {
$http.get('data.json')
.then(function(result) {
$scope.albums = result.data;
$scope.tracks = result.data.tracks;
console.log($scope.tracks); //Undefined...
});
});
Why is $scope.tracks undefined?
If your json file is as is:
[
{
"album": "Album name",
"tracks": [
{
"id": "1",
"title": "songtitle1",
"lyric": "lyrics1"
},
{
"id": "2",
"title": "songtitle2",
"lyric": "lyrics2"
}
]
}
]
We have a response of:
data: Array[1]
0: Object
album: "Album name"
tracks: Array[2]
Since data is returned as an array you would handle like any other javascript array and access by index, so you could do a loop or if you know only 1 result is going to be returned you could use the zero index:
$http.get('data.json').then(function(result) {
console.log(result);
// Assign variables
$scope.album = result.data[0].album;
$scope.tracks = result.data[0].tracks;
for (var i = 0, l = $scope.tracks.length; i < l; i++) {
console.log($scope.tracks[i].title);
}
});
result.data is an array,So you must have to use index to access its child like:-
$scope.tracks = result.data[0].tracks;
It should be result.data[0].tracks as data is an array
$scope.tracks = result.data[0].tracks;

jsonpath- Extracting json data using jsonpath

My json data is as follows:
"query": {
"count": 1,
"url": [
{
"execution-start-time": "1"
},
{
"execution-time": "745"
}
],
"service-time": "1481"
},
results": {
"div": {
"class": "makers",
"ul": {
"li": [
{
"a": {
"href": "nokia_x2_dual_sim-6383.php",
"img": {
"src": "Nokia-X2-Dual-SIM.jpg"
},
"strong": {
"br": null,
"content": "Nokia\nX2 Dual SIM"
}
}
},
{
"a": {
"href": "nokia_xl-6148.php",
"img": {
"src": "nokia-xl.jpg",
},
"strong": {
"br": null,
"content": "Nokia\nXL"
}
}
}
]
Now I want to extract the "content" part from this json data using jsonpath.I am using jsonpath-0.8.0.js for this purpose.
I have tried to parse the json data in the following way:
function ParseData(data) {
var result = jsonPath(data, "$.query.results[*].ul.li[*].strong.content");
$('#carousel').empty();
var html = "";
for (i = 0; i < result.length; i++) {
// do something
}
and I was expecting to get Nokia\nX2 Dual SIM and Nokia\nXL as output but this code of mine does not return anything.I cannot understand the problem.
How do I extract the content data from this json? please help.
Friends, I finally got the answer to my problem.I used the following code to extract content from the above given json data.
var result = jsonPath(data, "$.query.results[*].ul.li[*].a.strong.content");
Now I am getting the output data as expected.