I have a json that looks like this.
How can I retrieve the information inside the group "demo", without looking into the array like: json['data'][0] I wanted to retrieve the info reading the first value.. "group" and if it matches demo, get all that group info.
{
"filter": "*",
"data": [
{
"group": "asdasd",
"enable": 1,
"timeout": 7,
"otpMode": 0,
"company": "cool",
"signature": "ou yeah",
"supportPage": "",
"newsLanguages": [
0,
0,
0,
0,
0,
0,
0,
0
],
"newsLanguagesTotal": 0
},
{
"group": "demo",
"enable": 1,
"timeout": 7,
"otpMode": 0,
"company": "pppppooo",
"signature": "TTCM",
"supportPage": "http://www.trz<xa",
"newsLanguages": [
0,
0
],
"newsLanguagesTotal": 0
}
]
}
So long I have:
let json = JSON.parse(body);
//console.log(json);
console.log(json['data'][1]);
Which access to "demo"
Process each "data item" and check for the group value. If it matches, then do something.
var json = JSON.parse(jsonStr);
for(var i=0;i<json.data.length;i++){
if(json.data[i].group == "demo"){
var group = json.data[i];
// Process the group info
}
}
I suggest you use the filter()
json.data.filter(function(item){
return item.group === "demo";
});
this will return the objects that have "demo" in the group property
Or if you want to get fancy es6 with it
json.data.filter(item => item.group === "demo");
If the key "group" is missing for any of the records, a simple check (similar to the code provided by #MarkSkayff) will give an error. To fix this, check to see if json["data"][i] exists and check if json["data"[i]["group"] also exists
function json_data(){
var res=[]
for (var i in json["data"]){
if(json["data"][i] && json["data"][i]["group"] === "demo"){ //strict comparison and boolean shortcircuiting
res.push(json["data"][i])
}
}
console.log(res)
}
The result is stored in res
Not enough space here but for more on boolean short circuiting read this explanation of dealing with irregular JSON data
Related
I want to loop through 600+ array items in an object and find one particular item based on certain criteria. The array in the object is called "operations" and its items are arrays themselves.
My goal is to get the index of operation's array item which has the deeply nested string "Go".
In the sample below this would be the first element. My problem is that I can check if an array element contains "call" and "draw" but I don't know how to test for the nested dictionary "foobar". I only have basic JavaScript available, no special libraries.
let json = {
"head": {},
"operations": [
[
"call",
"w40",
"draw",
{
"parent": "w39",
"style": [
"PUSH"
],
"index": 0,
"text": "Modify"
}
],
[
"call",
"w83.gc",
"draw",
{
"foobar": [
["beginPath"],
[
"rect",
0,
0,
245,
80
],
["fill"],
[
"fillText",
"Go",
123,
24
],
[
"drawImage",
"rwt-resources/c8af.png",
]
]
}
],
[
"create",
"w39",
"rwt.widgets.Menu",
{
"parent": "w35",
"style": [
"POP_UP"
]
}
],
[
"call",
"w39",
"draw",
{
"parent": "w35",
"style": [
"POP_UP"
]
}
]
]
};
let index = "";
let operationList = json.operations;
for (i = 0; i < operationList.length; i++) {
if (operationList[i].includes('call') && operationList[i].includes('draw')) //missing another check if the dictionary "foobar" exists in this element )
{
index = i;
}
}
document.write(index)
I'll preface by saying that this data structure is going to be tough to manage in general. I would suggest a scheme for where an operation is an object with well defined properties, rather than just an "array of stuff".
That said, you can use recursion to search the array.
If any value in the array is another array, continue with the next level of recursion
If any value is an object, search its values
const isPlainObject = require('is-plain-object');
const containsTerm = (value, term) => {
// if value is an object, search its values
if (isPlainObject(value)) {
value = Object.values(value);
}
// if value is an array, search within it
if (Array.isArray(value)) {
return value.find((element) => {
return containsTerm(element, term);
});
}
// otherwise, value is a primitive, so check if it matches
return value === term;
};
const index = object.operations.findIndex((operation) => {
return containsTerm(operation, 'Go');
});
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]"
}
]
}
Given a JSON object such as this:
{
"something": {
"terms": [
{
"span": [
15,
16
],
"value": ":",
"label": "separator"
},
{
"span": [
16,
20
],
"value": "12.5",
"label": "number"
}
],
"span": [
15,
20
],
"weight": 0.005,
"value": ":12.5"
}
}
I asked a question about parsing the object out where label: number here:
JSON/Javascript: return which array object contains a certain property
I got a sufficient answer there (use filter()), but now need to know the original index of the object.
This issue seems to have the answer, but I simply don't know enough about javascript to translate it into something useful for my particular problem.
The following code successfully returns the object. Now I need to modify this to return the original index of the object:
var numberValue, list = parsed.something.terms.filter(function(a){
return a.label==='number';
});
numberValue = list.length ? list[0].value : -1;
This needs to be a pure javascript solution, no external libraries, etc.
I don't think you can modify the filter solution as within the filter you've lost the indexes.
The solution you've linked to uses the angular external library.
So here is a pure JS solution:
var numberValue = parsed.something.terms
.map(function(d){ return d['label']; })
.indexOf('number');
Array.prototype.indexOf()
Array.prototype.map()
Use forEach and collect the indices of objects that satisfy the a.label==='number' predicate :
var target = parsed.something.terms;
var list = [];
target.forEach(function(element, index){
if (element.label==='number') {
list.push(index)
};
});
var numberValue = list.length ? target[list[0]].value : -1;
console.log(list); // [1]
console.log(numberValue); // 12.5
I have this list i wanted to display on ng-table.
$scope.list = [
{
"moduleId": 1,
"name": "Perancangan",
"level": 0,
"childs": [
{
"moduleId": 12,
"name": "Perancangan Sektor",
"level": 1,
"childs": [],
"links": [
{
"rel": "self",
"href": "http://103.8.160.34/mrf/modules/1"
}
]
}
]
},
{
"moduleId": 2,
"name": "Pengurusan Pengguna dan Peranan",
"level": 0,
"childs": [
{
"moduleId": 17,
"name": "Pengurusan Pengguna",
"level": 1,
"childs": [],
"links": []
},
{
"moduleId": 18,
"name": "Operasi Peranan",
"level": 1,
"childs": [],
"links": []
}
],
"links": [
{
"rel": "self",
"href": "http://103.8.160.34/mrf/modules/2"
}
]
}
];
I wanted the list.childs to be the rows in the table with the list.name as grouping, i'd used ng-repeat to but doesn't work. The most i could do is display it as td. What im looking at is
Perancangan (header)
Perancangan Sektor
Pengurusan Pengguna dan Peranan
Here is the plunker
http://plnkr.co/edit/77t5id3WOmbl2GSqYKh2?p=preview
There seems to be at least two ways you could accomplish this. The first might be more simple but skirts the question you posed. Massage the list[] into a flattened and simplified array tailored for this table's view. You would then ng-repeat over that array.
That is really a dodge though and completely avoids your question. More directly to your question you could try to use nested ng-repeat's but those are pretty tricky. See: http://vanderwijk.info/blog/nesting-ng-repeat-start/
Finally, the approach that seems to best address you're question in both intent and spirit is to use a custom filter. I've written an example fiddle that should demonstrate the idea.
app.filter('flatten', function() {
// Because this filter is to be used for an ng-repeat the filter function
// must return a function which accepts an entire list and then returns
// a list of filtered items.
return function(listItems) {
var i,j;
var item, child;
var newItem;
var flatList = [];
// Begin a loop over the entire list of items provided by ng-repeat
for (i=0; i<listItems.length; i++) {
var item = listItems[i];
// Construct a new object which contains just the information needed
// to display the table in the desired way. This means we just extract
// the list item's name and level properties
newItem = {};
newItem.name = item.name.toUpperCase();
newItem.level = item.level;
// Push the level 0 item onto the flattened array
flatList.push(newItem);
// Now loop over the children. Note that this could be recursive
// but the example you provided only had children and no grandchildren
for (j=0; j<item.childs.length; j++) {
child = item.childs[j];
// Again create a new object for the child's data to display in
// the table. It also has just the name and level.
newItem = {};
newItem.name = child.name;
newItem.level = child.level;
flatList.push(newItem);
}
}
// Return the newly generated array that contains the data which ng-repeat
// will iterate over.
return flatList;
};
});
I have an JSON array like this
var filter_value_data = [{"Status":[{"name":"Open","id":"1"},{"name":"Pending","id":"2"},{"name":"Resolved","id":"3"},{"name":"Closed","id":"4"},{"name":"Evaluation","id":"5"}]},{"Payment Status":[{"name":"Paid","id":"10"},{"name":"UnPaid","id":"11"},{"name":"Part Paid","id":"12"}]},{"Priority":[{"name":"Low","id":"6"},{"name":"Medium","id":"7"},{"name":"High","id":"8"},{"name":"Urgent","id":"9"}]}]
I have tried filter_value_data["Status"] which is obviously wrong. How do I get the JSON elements for Status using the names like Status,Payment Status?
filter_value_data is an array (having []), so use filter_value_data[0].Status to get the first element-object with property "Status".
It is always good to format your code in order to see the hierarchy of the structures:
var filter_value_data = [
{
"Status": [
{
"name": "Open",
"id": "1"
}, {
"name": "Pending",
"id": "2"
}, ...
]
}, {
"Payment Status": [
{
"name": "Paid",
"id": "10"
}, ...
]
}, {
"Priority": [
{
"name": "Low",
"id": "6"
}, ...
]
}
];
With your current JSON you can't get the elements with the name alone.
You can get Status with filter_value_data[0]['Status'] and Payment status with filter_value_data[1]['Payment Status'].
This is because the keys are in seperate objects in the array.
In order to get them with filter_value_data['Status'] you need to change your JSON to
var filter_value_data = {
"Status":[
{"name":"Open","id":"1"},
{"name":"Pending","id":"2"},
{"name":"Resolved","id":"3"},
{"name":"Closed","id":"4"},
{"name":"Evaluation","id":"5"}
],
"Payment Status":[
{"name":"Paid","id":"10"},
{"name":"UnPaid","id":"11"},
{"name":"Part Paid","id":"12"}
],
"Priority":[
{"name":"Low","id":"6"},
{"name":"Medium","id":"7"},
{"name":"High","id":"8"},
{"name":"Urgent","id":"9"}
]
};
I wrote this on my phone so it's not as well-formatted as usual. I'll change it ASAP.
With your current JSON, created a result which might be helpful for you.
JS:
$.each(filter_value_data,function(ind,val){
var sta = val.Status; // Status Object get displayed
for(var i=0;i<sta.length;i++){
var idVal= sta[i].id;
var nameVal = sta[i].name;
Statusarray.push(idVal,nameVal);
console.log(Statusarray);
}
})
FiddleDemo
You can use below code, it will return status object
filter_value_data[0]['Status']
filter_value_data[0]['Payment Status']
to get Single value you use :
filter_value_data[0]['Status'][0]['name']