Get Values form Json, using jpath - json

{
"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

Related

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.

In AngularJS, Adding field to Array from another json file, possible callback issue

AngularJS Service:
Get json sub-record field for import into current open array record.
I have one json file with "services" in it (id, name) services.json,
I need to forEach through them, but as I am in each service I need to open sub-record(welding.json) and grab a field(title) and add it to the current record.
NOTE: My project is a CLI type.
services.json
[
{
"id": 1,
"name": "welding"
},
{
"id": 2,
"name": "carpentry"
},
{
"id": 3,
"name": "mechanic"
}
]
= Sub-Records =
welding.json
{
"category": "labor",
"title": "Arc Welding",
"description": "",
"experience": "20+ Years",
"details": ""
}
Expectation:
{
"id": 1,
"name": "welding",
"title": "Arc Welding"
}
Try this
angular.forEach($scope.services, function (value, key) {
if(value.name == 'welding'){
$http.get('welding.json').then(function (response) {
$scope.welding = response;
})
$scope.services.title=$scope.welding.title;
}});

JSON transformation in node.js

I want to transform my data from one json structure to another. What is the best way to do it?
Here is my original resource (customer) structure is:
{
"id": "123",
"data": {
"name": "john doe",
"status": "active",
"contacts": [
{
"email": "john#email.com"
},
{
"phone": "12233333"
}
]
}
}
I want to change it to:
{
"id": "123",
"name": "john doe",
"status": "active",
"contacts": [
{
"email": "john#email.com"
},
{
"phone": "12233333"
}
]
}
Keeping in mind that I might have an array of resources(customers) being returned in GET /customers cases. I want to change that to an array of new data type.
If customer object is array of object then below will help you to get desire format result
var result = customerObj.map(x => {
return {
id: x.id,
name: x.data.name,
status: x.data.status,
contacts: x.data.contacts
};
});
here I have used Object.assign() it will be helpful to you
var arr={
"id": "123",
"data": {
"name": "john doe",
"status": "active",
"contacts": [
{
"email": "john#email.com"
},
{
"phone": "12233333"
}
]
}
}
arr=Object.assign(arr,arr.data);
delete arr['data'];
console.log(arr);
You have to Json.parse the json into variable, and then loop through the array of objects, changes the object to the new format, and then JSON.stringify the array back to json.
Example code
function formatter(oldFormat) {
Object.assign(oldFormat, oldFormat.data);
delete oldFormat.data;
}
let parsedData = JSON.parse(Oldjson);
//Take care for array of results or single result
if (parsedData instanceof Array) {
parsedData.map(customer => formtter(customer));
} else {
formatter(parsedData);
}
let newJson = JSON.stringify(parsedData);
console.log(newJson);
Edit
I made the formatter function cleaner by using Kalaiselvan A code

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;

evaluating json object returned from controller and attaching it to prepopulate attribute of tokeninput

I am using loopjs tokeninput in a View. In this scenario I need to prePopulate the control with AdminNames for a given Distributor.
Code Follows :
$.getJSON("#Url.Action("SearchCMSAdmins")", function (data) {
var json=eval("("+data+")"); //doesnt work
var json = {
"users": [
eval("("+data+")") //need help in this part
]
}
});
$("#DistributorCMSAdmin").tokenInput("#Url.Action("SearchWithName")", {
theme: "facebook",
preventDuplicates: true,
prePopulate: json.users
});
There is successful return of json values to the below function. I need the json in the below format:
var json = {
"users":
[
{ "id": "1", "name": "USER1" },
{ "id": "2", "name": "USER2" },
{ "id": "3", "name": "USER3" }
]
}