How to parse multilevel json using Javascript/Jquery - javascript

I am very new to JSON, stuck in parsing multi level JSON array, I want to parse it using javascript or jquery. From the JSON I want to get application id, application description & Product description
[
{
"roadMapData": [
{
"applicationDetail": [
{
"applicationDescr": "R25updated-R25updated",
"applicationId": 352
}
]
},
{
"productSubGrupDetail": [
{
"productGroupId": 271,
"productSubGroupDes": "TEST123-TEST1234"
}
]
},
{
"productSubGrupDetail": [
{
"productGroupId": 278,
"productSubGroupDes": "ggg-hhhh"
}
]
}
]
},
{
"roadMapData": [
{
"applicationDetail": [
{
"applicationDescr": "R25updated-R25updated",
"applicationId": 352
}
]
},
{
"productSubGrupDetail": [
{
"productGroupId": 271,
"productSubGroupDes": "TEST123-TEST1234"
}
]
},
{
"productSubGrupDetail": [
{
"productGroupId": 278,
"productSubGroupDes": "ggg-hhhh1"
}
]
}
]
}
]
Thanks in advance :)

Here is the Demo
Check jQuery.parseJSON
var jsonObj = jQuery.parseJSON(jsonString);
for (i = 0; i < jsonObj.length; i++) {
var roadMapData = jsonObj[i].roadMapData;
var applicationDetail = roadMapData[0].applicationDetail; //First Object
var productSubGrupDetail1 = roadMapData[1].productSubGrupDetail; //Second Object
var productSubGrupDetail2 = roadMapData[2].productSubGrupDetail; //Third Object
console.log(applicationDetail[0].applicationDescr); //applicationDetail's First Object
console.log(productSubGrupDetail1[0].productGroupId); //productSubGrupDetail1's First Object
console.log(productSubGrupDetail2[0].productSubGroupDes); //productSubGrupDetail2's First Object
}

If data initially presented in JSON (as a string), you need first parse it into JavaScript object with JSON.parse(json). Then you can access any property with object dot notation. If you are not familiar with objects in JavaScript, check this article.

Related

How can I go about replacing a number array inside a json string in SQL?

The data in SQL contains a lengthy JSON string in a cell similar to this:
{
"Name": "Example",
"Results": [
{
"ResultId": 0,
"AnswerIds": "[1,2,33,4,5]"
},
{
"ResultId": 1,
"AnswerIds": "[2,3,4,55,6]"
}
]
}
I have a list of replacement AnswerIds: Replace all 2 with 7, all 3's with 8's
How can I go about making a script for this?
I'm able to isolate the AnswerIds using crossapply and JSON_Query, but not sure how to go about replacing several changes in one array.
const json = {
"Name": "Example",
"Results": [
{
"ResultId": 0,
"AnswerIds": "[1,2,33,4,5]"
},
{
"ResultId": 1,
"AnswerIds": "[2,3,4,55,6]"
}
]
}
json.Results.forEach((itm, index)=> {
const arr = JSON.parse(itm.AnswerIds);
const replacedArray = arr.map(num=>{
if(num === 2) return 7;
if(num === 3) return 8;
return num;
});
json.Results[index].AnswerIds = JSON.stringify(replacedArray);
})
console.log(json);
This is what I have done, Take the json.Results array and iterate it with a forEach loop.
You can then access the AnswerIds object of each result.
Since the AnswerIds value is a string, we first convert it to an array.
Then we loop throught that array using a map, and do the replacements.
You might want to read up on JS maps, and JS foreach, JSON.parse, JSON.stringify
SQL Server 2016 has JSON support but you did not specify your SQL version.
Using DelimitedSplit8k you can do this:
-- SAMPLE STRING
DECLARE #string VARCHAR(1000) =
'{
"Name": "Example",
"Results": [
{
"ResultId": 0,
"AnswerIds": "[1,2,33,4,5]"
},
{
"ResultId": 1,
"AnswerIds": "[2,3,4,55,6]"
}
]
}';
-- SOLUTION
SELECT NewJSON =
(
SELECT
IIF(i.pos = 0,IIF(i.pos>0 AND sub.string IN(2,3), x.x, sub.string),
IIF(s2.ItemNumber=1,'"[','')+IIF(i.pos>0 AND sub.string IN(2,3),x.x,sub.string)) +
IIF(s2.ItemNumber>LEAD(s2.ItemNumber,1) OVER (ORDER BY s.ItemNumber,s2.ItemNumber),']"',
IIF(i.pos = 0,'',','))
FROM dbo.delimitedsplit8k(REPLACE(#string,CHAR(13),''),CHAR(10)) AS s
CROSS APPLY (VALUES(CHARINDEX('"AnswerIds": "',s.item))) AS i(pos)
CROSS APPLY (VALUES(SUBSTRING(s.item, i.pos+14, 8000))) AS ss(item)
CROSS APPLY dbo.delimitedsplit8k(ss.item,IIF(i.pos=0,CHAR(0),',')) AS s2
CROSS APPLY (VALUES(IIF(i.pos=0,s.item,
REPLACE(REPLACE(s2.item,']"',''),'[','')))) AS sub(string)
CROSS APPLY (VALUES(REPLACE(REPLACE(sub.string,'2',7),'3',8))) AS x(x)
ORDER BY s.ItemNumber, s2.ItemNumber
FOR XML PATH('')
);
Returns:
{
"Name": "Example",
"Results": [
{
"ResultId": 0,
"AnswerIds": "[1,7,33,4,5]"
},
{
"ResultId": 1,
"AnswerIds": "[7,8,4,55,6]"
}
]
}

Returning an array of objects from other object

Hello am trying to extract some information from an object to create a graph but it returns undefined my object looks like
{
"concepts": [
{
"id_cpt": "1",
"fr_cpt": "Proche",
},
{
"id_cpt": "2",
"fr_cpt": "Loin",
}{
"id_cpt": "3",
"fr_cpt": "Here",
},...
],
"arcs": [
{
"idfrom":"1",
"idto":"2"
},
{
"idfrom":"3",
"idto":"2"
},....
]
}
I want to make an object looks like
const data = {
nodes: [{ id: 'Proche' }, { id: 'Loin' },{ id: 'Here' } ...],
links: [{ source: 'Proche', target: 'Loin' }, { source: 'Here', target: 'Loin' },...]
};
I want extract names not ids in links but the object arcs only have ids the code in es6 and thank you for helping me
You could loop through the concepts using for...of. Populate the nodes array and a map object. The map object has id_cpt as key and fr_cpt as value.
{
"1": "Proche",
"2": "Loin",
"3": "Here"
}
This object can be used to get the source and target value for links. Then loop through arcs and create links using map object
Here's a snippet:
const input = {"concepts":[{"id_cpt":"1","fr_cpt":"Proche",},{"id_cpt":"2","fr_cpt":"Loin",},{"id_cpt":"3","fr_cpt":"Here",},],"arcs":[{"idfrom":"1","idto":"2"},{"idfrom":"3","idto":"2"},]}
let nodes = [],
links = [],
map = {};
for (const { id_cpt, fr_cpt } of input.concepts) {
nodes.push({ id: fr_cpt });
map[id_cpt] = fr_cpt
}
for (const { idfrom, idto } of input.arcs) {
links.push({ source: map[idfrom], target: map[idto] }) // get the value using map
}
const output = { nodes, links }
console.log(output)

Insert array of objects to database

I have the following array containing objects, And there are arrays in the objects too.
let array = [
{
"data": {
"Game": {
"Game_number": [
"4",
"6",
"8"
],
"Game_name": [
"Name_1",
"Name_2",
"name_3"
]
},
"AA": {
"AA_count": [
"30"
],
"AA_name": [
"Umbrella"
]
},
}
}
]
Now i have to put them in database, Each have a column against.
But the issue is that the above data is not constant, So i cannot put them via their indexes. if the data is missing for a column than that's fine it will go empty
I tried via for each but that is inserting the last element of the array.
array.data.forEach((item) => {
const Games = Parse.Object.extend('Games');
const query = new Games();
item.data.Game.Game_number.forEach((number) => {
query.set('game_number', number);
}, this);
item.data.Game.Game_name.forEach((name) => {
query.set('game_name', name);
}, this);
query.save();
}, this);
What will be a flexible way to handle it ?

Filter JSON to contain only desired values

I've been working on this for a while now and I can't seem to figure it out. I have a JSON that I am pulling in from a link, and I'm trying to create a filter so that only names that start with a certain keyword show up.
I've been trying to use .parseJson and also I've tried str.includes() but I can't seem to get either working right.
Here's a piece of what the JSON looks like:
[
{
"max_percentile_90th": 42142.1,
"daily_percentile_50th": 21334.5,
"timerName": "Booklet:Landscape",
"sparks": [
26651,
23801.2,
20850.8,
19157.4,
21198.5,
],
},
{
"max_percentile_90th": 59253.4,
"daily_percentile_50th": 9040.5,
"timerName": "Search:Blog",
"sparks": [
9248.1,
13653,
8277,
9532.2,
10912.4,
],
},
{
"max_percentile_90th": 16707.9,
"daily_percentile_50th": 3793,
"timerName": "Search:Records:Download",
"sparks": [
6257.6,
8269,
9395.4,
6211.4,
9420.7,
],
},
{
"max_percentile_90th": 6979.4,
"daily_percentile_50th": 2821,
"timerName": "Search:AfterEffects",
"sparks": [
3752.2,
4522.8,
6167.2,
3847.9,
4568.9,
],
},
{
"max_percentile_90th": 5900.8,
"daily_percentile_50th": 2323,
"timerName": "Booklet:Geneologies",
"sparks": [
3359.2,
3317.8,
3113.5,
2839,
2675.6,
],
}
]
So as you can see, the timerName STARTS with "Booklet" (but had different things after it) on two of them and starts with "Search" on three of them. The JSON is much longer, but this snippet will get my point across. So I want to make a filter that will only show the ones that start with "Search" or only show the ones that start with "Booklet". I need all the data associated with it though, because I'm making a table, so is it possible to make a new JSON based on that? Or how should I go about this?
Here is a fiddle from what I've tried: http://jsfiddle.net/xjcfw7zf/
Any help is much appreciated! Thank you!!
To filter objects that start with "Booklet" can be achieved by following
jsonData = jsonData.filter(function(obj){
return (obj.timerName.indexOf("Booklet") == 0)
});
For reference - http://jsfiddle.net/xjcfw7zf/3/
Note - To be more generic, you can have a variable as well in place of "Booklet"
Use .filter() and .indexOf. Filter will iterate through each object and filter based on a condition. indexOf will tell if the given key is present in the string.
function search(data, key) {
return data.filter(function(item) {
return item.timerName.indexOf(key) == 0;
});
}
var jsonData = [{
"max90th": 42142.1,
"daily90th": 21334.5,
"timerName": "Booklet:Landscape",
"sparks": [
26651,
23801.2,
20850.8,
19157.4,
21198.5,
],
}, {
"max90th": 59253.4,
"daily90th": 9040.5,
"timerName": "Search:Blog",
"sparks": [
9248.1,
13653,
8277,
9532.2,
10912.4,
],
}, {
"max90th": 16707.9,
"daily90th": 3793,
"timerName": "Search:Records:Download",
"sparks": [
6257.6,
8269,
9395.4,
6211.4,
9420.7,
],
}, {
"max90th": 6979.4,
"daily90th": 2821,
"timerName": "Search:AfterEffects",
"sparks": [
3752.2,
4522.8,
6167.2,
3847.9,
4568.9,
],
}, {
"max90th": 5900.8,
"daily90th": 2323,
"timerName": "Booklet:Geneologies",
"sparks": [
3359.2,
3317.8,
3113.5,
2839,
2675.6,
],
}];
function search(data, key) {
return data.filter(function(item) {
return item.timerName.indexOf(key) == 0;
});
}
alert(search(jsonData, "Booklet").length);
alert(search(jsonData, "Search").length);
alert(search(jsonData, "Something").length);
How about iterating over the main array in your JSON object using a for loop, perfoming a comparison using substring on the current iteration object's timerName property, and then putting that into a result array on match, only to finally return that array?
/**
* #param {array} json
* #param {string} filter
*/
function itemsByTimerName(json, filter) {
var filtered = [];
for (var i = 0; i < json.length; ++i) {
// if 'timerName' begins with 'filter'
if (json[i].timerName.substring(0, filter.length) === filter) {
filtered.push(json[i]);
}
}
return filtered;
}
Use a library such as lodash, to filter based on which ever key and value you are trying to find, in lodash you would want to use "pluck" for what you are after. Lodash is a very useful library which enables you to do all sorts of things with JSON objects, and javascript in general.
https://lodash.com/docs#filter

Proper way in Mongo to update the value of a key without removing old values?

I'm trying to get the following to work but $set's not working. Scratching my head.
What we have in Mongo:
{
_id: "123",
mechanics: {
engine: [
"129hp",
"300hp",
"500hp"
]
}
}
The object that we have in our javascript:
{
mechanics: {
brakes: [
"30cm",
"60cm",
"90cm"
]
}
}
How do you write the update query to make the Mongo doc look like this?
{
_id: "123",
mechanics: {
engine: [
"129hp",
"300hp",
"500hp"
],
brakes: [
"30cm",
"60cm",
"90cm"
]
}
}
Doing $set on mechanics doesn't work because it erases engine and adds in brakes.
What you basically want is "dot notation" which means that your update portion with $set comes out like this:
{ "$set" : { "mechanics.brakes" : [ "30cm", "60cm", "90cm" ] } }
To process an object in JavaScript like you show into this form you would do something like this:
var upd = { "$set": {} };
var obj = {
mechanics: {
brakes: [
"30cm",
"60cm",
"90cm"
]
}
};
Object.keys( obj ).forEach(function(top) {
Object.keys( obj[top] ).forEach(function(inner) {
upd["$set"][ top + "." + inner ] = obj[top][inner]
});
})
Which forms the update statement from the basic obj input and updates the database as you want.

Categories