I'm new to JS an this is likely a noob question, but I can't seem to find an answer which I figure may be due to my lack of correct terminology.
Basically I'm trying to count how many "active" fields in a JSON file are set to true vs false and return those values to a variable. I'm just getting lost trying to figure out how to go about this.
For example, my JSON is named data and looks like this:
{
"systems": [
{
"name": "SV001",
"IP": "10.1.1.101",
"active": "true"
},
{
"name": "SV002",
"IP": "10.1.1.102",
"active": "true"
},
{
"name": "SV003",
"IP": "10.1.1.103",
"active": "false"
}
]}
Any help would be greatly appreciated.
You could parse into the json object from string like
var json=JSON.parse(jsonString); And than by looping you can get the value.
var count=0;
for(var i=0i<json.systems.length;i++){
if(json.systems[i].active){
count++;
}
}
you can have count at the end of loop.
Related
I have a collection named templates. It has a field 'sec_1' which is an array of objects with properties 'name' and 'des' both of type string. Now I'm using elastic search and when I try to execute a query that matches only title fields I get an error saying the sec_1 field is not nested. Upon checking the mappings here is what I get mapping type of sec_1 is text.
I checked online and saw the fix was to modify the mapping. I created a new index like:
`curl base_url/new_index_name
{
"mappings":
{"properties": {
"sec_1": {
"type":
"nested","properties": {
"name": { "type": "text" },
"des": { "type": "text" }
}
}
}
}
}
and then reindexed like this:
curl base_url/_reindex
{
"source": {
"index": "old_index"
},
"dest": {
"index": "new_index"
}
}`
First request is successful, the second one fails with this error:
{
"index": "new_index",
"type": "_doc",
"id": "be5123a4-d0e8-4d7b-a8f1-42f31d37fe55",
"cause": {
"type": "mapper_parsing_exception",
"reason": "object mapping for [sec_1] tried to parse field [null] as object, but found a concrete value"
},
"status": 400
},
I don't understand why this is happening and what I'm doing wrong. Please help. I do not know much about elastic search, I've looked for solutions online, tried chatgpt too but the same steps appear. I'm finding the reason for this error is that sec_1 is not nested type but I've checked in database it is an array of objects. What else could be wrong?
I tried creaing new index but cannot do that and without new index my search query cant function properly
I have a problem getting access to the variables in a JSON-File. I get the file as a response from a REST-API. Here you can see the JSON-File:
{
"_embedded": {
"events": [
{
"name": "Josh.",
"type": "event",
"id": "Z698xZC2Z17CebP",
"test": false,
"url": "https://www.ticketmaster.de/event/josh-tickets/382625?language=en-us",
"locale": "en-us"
I want to access the value (Josh) of the "name" variable in Javascript in line number 5 and store it into a new variable to use it later.
This ist how I try to do it:
var = data._embedded.events[0].name
But I can't get access to the value attached to "name".
I have read the answers to similar questions here, but there was no solution for me.
I have only read, that it does not work because of the wrong JSON-structure. In other threads, they say there has to be a "{" instead of a "[" in line 3. But I don't know how to change it in javascript directly. I tried it with the JSON.stringify()-method but it didn't work out.
Can somebody help me, please? Is there any way to get access?
I hope you can understand my problem.
Thank you very much!
It seems that your json structure has some errors. The json structure similar to the following is legal. Of course, it is no problem to use a legal structure to exec data._embedded.events[0].name.
const data = {
"_embedded": {
"events": [
{
"name": "Josh.",
"type": "event",
"id": "Z698xZC2Z17CebP",
"test": false,
"url": "https://www.ticketmaster.de/event/josh-tickets/382625?language=en-us",
"locale": "en-us"
},
{
"name": "Josh.",
"type": "event",
"id": "Z698xZC2Z17CebP",
"test": false,
"url": "https://www.ticketmaster.de/event/josh-tickets/382625?language=en-us",
"locale": "en-us"
},
//...
]
}
}
console.log(data._embedded.events[0].name)
I am trying to find a way to populate form with multitiude of option types, selects , radios, texareas, checkboxes. I found few scripts like jQuery populate plugin or suggestions here Using jQuery and JSON to populate forms? and many more stack posts but none of them handle the multidimensional JSON data properly. This is the small sample of JSON data I am dealing with ,
var jsonData = {
"get_template": "clean",
"site_width": "1200px",
"layout_type": "full",
"main_contained": {
"picked": "contained",
"notcontained": {
"container_contained": "contained"
}
},
"container_spacing": "25",
"columns_spacing": "25",
"sidebars_spacing": {
"horizontal": "50",
"vertical": "50"
},
"headers": "menuright",
"menu_template": "menuinheader",
"toplevel_font": {
"font": "Open Sans|600|latin|uppercase|default",
"size": "12",
"letterspacing": "0",
"css": "font-family:'Open Sans',sans-serif;font-weight:600;font-style:normal;font-size:12px;text-transform:uppercase;",
"google_font_link": "Open Sans:600&subset=latin"
},
"sublevel_font": {
"font": "Open Sans|regular|latin|none|default",
"size": "14",
"letterspacing": "0",
"css": "font-family:'Open Sans',sans-serif;font-weight:normal;font-style:normal;font-size:14px;",
"google_font_link": "Open Sans:regular&subset=latin"
},
"footer_switch": 1,
"show_button": {
"picked": "hide",
"show": {
"button": {
"button_text": "Load more",
"html": "<div class=\"btn-container grid-item-more\"><a class=\"button btn-small radius-4 btn-border-1 align-center btn-trans\" href=\"#\"><span class=\"btn-text fs-13 fw-600\">more</span></a></div>",
"json": "{\"createButton\":\"on\",\"buttonTransition\":\"on\",\"buttonAnimation\":false}"
}
}
},
"img-smaller": {
"max-width": "260",
"max-height": "145"
},
"img-xsmall": {
"max-width": "120",
"max-height": "65"
},
"img-related": {
"max-width": "350",
"max-height": "350"
},
"custom_css": 0,
"disable_admin_bar": false,
"footer_section": {
"json": "[{\"type\":\"section\",\"shortcode\":\"section_e603095\",\"width\":\"\",\"_items\":[{\"type\":\"columns\",\"shortcode\":\"columns_a9ae4ee\",\"width\":\"1_3\",\"options\":{\"widget_name\":\"Widget 1\",\"widget_in_boxstyle\":{\"padding\":{\"top\":\"0\",\"right\":\"0\",\"bottom\":\"0\",\"left\":\"0\"}]"
}
};
and as you can see the form can have text , json, booleans, and so on as values.
Form input names are prefixed like this fw_options[link_color] or fw_options[main_contained][picked]
If I could ad least find a way to properly loop trough this json to rebuild the input names in the right way I might get a way with just checking the input type and setting its value.
Any help is appreciated.
Unfortunately, the code will be a mess, buts here's what you need to do.
Figure out how to loop for all of them, unfortunately I can only suggest that somewhere you call itself with a child such the below code using mock variables:
function jsonloop(looper){ //pass in object/array to loop through
if(lastchild){ //if last child of the lower part
upperchild++; //go to next child of upper part
jsonloop(upperchild);
}
}
Use instanceof to check the type:
if(json instanceof Array){
for(var item in json){
var jsonarray = json[item];
//do stuff
}
} else if(json instance of Object){
for(var item in json){
var jsonobject = json[item];
//do different stuff like below
for(var name in jsonobject){ //loop through object properties
//do other stuff
}
}
}
This is all mock code!
Do not use as it is, it will not end well. Note: The end result will likely be semi-massive due to stuff like, "json": [{}] where is both an object and an array, and you're code will bomb. Here are some good resources:
JSON name iteration
Convert to array (may or may not be useful).
Find if json array (also works with object, just replace with Object).
Good luck. I'm sorry, I couldn't build more.
I have the following JSON, I want add commas in between the numbers, but when ever I do that the JSON fails. My workign version of the code can be seen in the fiddle link below
FIDDLE
I want to change this 11488897 to 11,488,897
Is this possible to do? How can this be done?
thanks for your help
[{
"name": "",
"data": ["Totals","Total1 ","Total 2","total 3" ]
}, {
"name": "Amount1",
"data": [48353330,38079817,37130929,1957317]
}, {
"name": "Amount2",
"data": [11488897,8902674,8814629,497369]
}]
If you want to preserve commas, you just need to use strings:
"data": ["48,353,330","38,079,817","37,130,929","1,957,317"]
Whether that's a good idea or not is another story. Typically you'd want your JSON returned by the server to include raw (i.e., integer) data, and then just format it however you want when you're actually using it. That way the same RPC endpoint can be used to fetch data for use in a chart or for any other purpose that might arise later on.
try this:
var data = [{
"name": "",
"data": ["Totals","Total1 ","Total 2","total 3" ]
}, {
"name": "Amount1",
"data": [48353330,38079817,37130929,1957317]
}, {
"name": "Amount2",
"data": [11488897,8902674,8814629,497369]
}];
data.forEach(function(obj) {
obj.data = obj.data.map(function(item) {
if (typeof item == 'number') {
return item.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
} else {
return item;
}
});
});
alert(JSON.stringify(data, true, 4));
I don't know if it's cross-browser but if you do this
var number = 11488897;
number = number.toLocaleString('en');
You'll get the number (string) with commas on decimals
The data which I fetch from PHP page is like:
[{
"id": "1",
"name": null,
"startdate": "2012-07-20",
"starttime": "09:53:02",
"enddate": "2012-07-20",
"endtime": "09:54:10",
"duration": "01:00:00",
"feedbacks": [{
"id": "1",
"type": "1",
"content": "cont"
}],
"conditions": [{
"id": "1",
"dev_id": "1",
"mod_id": "2",
"sub_id": "3",
"to_be_compared_value": "1",
"comparison_type": "1"
}],
"actions": [{
"id": "1",
"dev_id": "1",
"mod_id": "1",
"sub_id": "1",
"target_action": "1"
}]
}]
Which way is easy, efficent and elegant to traverse this object? I used this two until this time. Can you tell me which one must be my choice, or can you give me an alternative? And why? I have a running version of my application and I'm reviewing now my own code, and I want to take some advices from you all.
Thanks in advance,
Methods I use before:
$.map
for(var i in obj)
One more to go, I will create a table from this data.
I would use jQuery's each() (or map() if I wanted to change the data)
I should add that you should also create a function which returns an object (possibly even with some utility methods), since your data isn't very JS-friendly right now. Those dates and times, those ID's as strings.
Example:
function cleanMyObject(object){
var cleanFeedbacks = function(feedbacks){
/* ... */
return feedback;
};
object.start = /* transform date and time strings to datetime object ...*/
object.end = /*...*/
/*...*/
$.map(object.feedbacks,cleanFeedbacks);
/* cleanup the remaining objects... */
return object;
}
$.map(receivedData, cleanMyObject);
// cleanMyObject() returns the modified object so $.map will clean everything in your array.
I prefer to use http://underscorejs.org/ for things like this. It has a lot of useful functions for objects, collections etc.
If the data you are recieving doesn't change, just parse the object and use the keys you need.
All browsers I'm aware of have a function called JSON.parse to convert a JSON string into a JS object.
What I'm trying to say is: Don't be lazy, you aren't gaining any benefits from writing a "general" function if your object will always provide the same data, and there is little to no chance you can use that function again with a different object.
var myobj= JSON.parse(phpJSONstring);
var feedbacks= myobj["feedbacks"];
//do something with feedbacks
var conditions= myobj["conditions"];
//do something with conditions
etc
You can transform the json string in a javascript object, and then access the object like this:
var obj = jQuery.parseJSON(jsonString);
alert('Id='+obj.id);
var feedbackList = obj.feedbacks;
for (var i=0; i<feedbackList.length; i++) {
...
}
Reference to jQuery.parseJSON: http://api.jquery.com/jQuery.parseJSON/