How to extract json, multiple value using jquery - javascript

Hello I have a json data like this
KLOBS {"SL_VEF_APPLIED_VS_BOL_R1_KLOBS":["0.00247320692497939","0.000008129750823137272"]}
KL15 {"SL_VEF_APPLIED_VS_BOL_R1_KL15":["0.01890831252229754","0.9008162336184189"]}
I'm already try extract json
$.get('url_request.php?' + $(this).serialize(), function(data) {
var obj = data;
$.each(obj, function(key, value) {
console.log(key);
console.log(value);
});
});
$.each(obj, function(key, value) {
console.log(key);
console.log(value);
});
And I get result
KLOBS
{"SL_VEF_APPLIED_VS_BOL_R1_KLOBS":["0.00247320692497939","0.000008129750823137272"]}
KL15
{"SL_VEF_APPLIED_VS_BOL_R1_KL15":["0.01890831252229754","0.9008162336184189"]}
I want to get result like this:-
KLOBS
0.00247320692497939
0.000008129750823137272
KL15
0.01890831252229754
0.9008162336184189
How to call json like this ??
I don't know call multiple value data in Json.
Please help me.

Try this
var arr = {
KLOBS: {
SL_VEF_APPLIED_VS_BOL_R1_KLOBS: [
"0.00247320692497939",
"0.000008129750823137272"
]
},
KL15: {
SL_VEF_APPLIED_VS_BOL_R1_KL15: ["0.01890831252229754", "0.9008162336184189"]
}
};
Object.keys(arr).forEach(function(key, value) {
console.log(key);
Object.keys(arr[key]).forEach(function(val) {
arr[key][val].forEach(function(data) {
console.log(data);
});
});
});

In general you could do the following:
var KLOBS = {"SL_VEF_APPLIED_VS_BOL_R1_KLOBS":
["0.00247320692497939","0.000008129750823137272"]}
values = Object.keys(KLOBS).map(x=>{
return KLOBS[x];
})
values.forEach(x=>x.forEach(y=>console.log(y)))
jsfiddle
Object.keys gives you an array of the keys in an object.
Since I do not know the structure in advance, I assume it better thinking of more than one key.
With the function map, a function is applied to each member of the array returned by Object.keys. This is used to extract the values.
The resulting structure is an array of arrays.
Therefore a double forEach is needed to display every entry of the structure.

Related

Loop ONLY through a defined JSON object in a nested structure - JQUERY

I have the following json structure (I've made it shorter for simplify):
{
"employees":{"0":"Name1 Surname1", "1":"Name2 Surname2"},
"managers":{"0":"Name3 Surname3", "1":"Name4 Surname4"},
"teamleaders":{"0":"Name5 Surname5", "1":"Name6 Surname6"},
}
How can I loop ONLY through employees with JQuery? The below code gives me the whole 3 objects and I can't seem to be able to sort them according to the object name:
$.each(item, function (i, item) {
$.each(item, function (key, value) {
//gives me ALL names and surnames
console.log(value);
})
});
You can use plain JS for this.
for (var employee in json.employees) {
if (json.employees.hasownProperty(employee))
console.log(json.employees[employee])
}
Instead of iterating the outer object, item, do like this.
var item = {
"employees":{"0":"Name1 Surname1", "1":"Name2 Surname2"},
"managers":{"0":"Name3 Surname3", "1":"Name4 Surname4"},
"teamleaders":{"0":"Name5 Surname5", "1":"Name6 Surname6"},
}
$.each(item.employees, function(key, value) { ... });

Trying to iterate over json string

I'm trying to iterate over this json encoded array which is a string:
"{"":{"count":{"total":112,"open":0,
"solved":0,
"deleted":106,
"closed":6},
"average_time_open_in_minutes":206,
"tickets_fortnight_week_count":11,
"tickets_last_week_count":15,"trend":1},
"Net2grid":{"count":"total":8,"open":0,"solved":0,"deleted":8},"average_time_open_in_minutes":0,"tickets_fortnight_week_count":0,"tickets_last_week_count":0,"trend":0},"Closed_by_merge":{"count":{"total":2,"open":0,"solved":0,"closed":2},"average_time_open_in_minutes":502,"tickets_fortnight_week_count":0,"tickets_last_week_count":0,"trend":0},"Analytics":{"count":{"total":1,"open":0,"solved":0,"deleted":1},"average_time_open_in_minutes":26,"tickets_fortnight_week_count":0,"tickets_last_week_count":0,"trend":0},"Meter":{"count":{"total":5,"open":5,"solved":0},"average_time_open_in_minutes":0,"tickets_fortnight_week_count":0,"tickets_last_week_count":2,"trend":1},"Installation":{"count":{"total":8,"open":5,"solved":3},"average_time_open_in_minutes":404,"tickets_fortnight_week_count":0,"tickets_last_week_count":0,"trend":0},"Other...":{"count":{"total":3,"open":2,"solved":1},"average_time_open_in_minutes":39,"tickets_fortnight_week_count":0,"tickets_last_week_count":0,"trend":0},"Meter Offline":{"count":{"total":8,"open":7,"solved":1},"average_time_open_in_minutes":8,"tickets_fortnight_week_count":0,"tickets_last_week_count":0,"trend":0},"App Usage":{"count":{"total":6,"open":5,"solved":0,"deleted":1},"average_time_open_in_minutes":8,"tickets_fortnight_week_count":0,"tickets_last_week_count":0,"trend":0}}"
An ajax call returns that string and i'm trying to only get the keys like: "app usage" and "Meter Offline" to return like so:
$.get('/ajax/ticket-and-notes-data.php', function (data) {
var problems = getProblems(data);
function getProblems(problems) {
var problemCategories = [];
$.each(JSON.parse(problems), function (key, value) {
if (key != "") {
problemCategories.push = key;
}
});
return problemCategories;
}
});
But I can't get the keys to go into the problemCategories.
I use this to set the categories in a highchart bubble chart and I will use more of the data from the string later.
I need to get this to work first.
The issue is in the way that you're using array.push. You should use array.push(item) instead of array.push = item.

Access the nested value in JSON without looping through it

This is my JSON, I want to directly get the zipCodes values from the JSON without looping through the JSON. How can I do it?
countries:[
{
name:'India',
states:[{
name:'Orissa',
cities:[{
name:'Sambalpur',
zipCodes:{'768019','768020'}
}]
}]
}
]
I think you are looking for
countries[0].states[0].cities[0].zipCodes
Please note, this works for the above JSON as there is only 1 country in countries array and same as for states and cities. However, if there are more than 1 country, state or city then, you will have to iterate to extract information until and unless you know the exact index.
As this is not an associative array, your option is only to use indexes like this:
countries[x].states[y].cities[0].zipCodes
Where x would be each representation of state in your array, in case, of course, that you have more than one.
Similarly y would be each state in each state in each country, in case you have more of those and you can do the same for cities if you need to.
EDIT:
Here's how you can iterate the array:
for(var c in countries)
{
var name = countries[c].name;
if (name === "CountryIAmLookingFor")
{
var statesList = countries[c].states;
for (var s in statesList)
{
var stateName = statesList[s].name;
.....
}
}
}
You can keep iterating until you find the country, state, and city you need, then extract the zipCodes from there as shown in the previous code snippet.
Without "looping"
You can do this crazy trick (not saying this is the best way, but this way you aren't looping through the JSON):
var myData = { 'Put Your Data': 'HERE' };
function getCodes(name, data) {
var sv = data.match(new RegExp(name+'([\\S\\s]*?}][\\S\\s]*?}])'))[1].match(/zipCodes":\[(.*?)\]/g), r = [];
sv.forEach(function (item) {
item.match(/\d+/g).forEach(function (sub) {
r.push(+sub);
});
});
return r;
}
getCodes('India', JSON.stringify(myData));
If your data is already string, then you don't need the JSON.stringify. The forEach you see isn't actually "looping" through the JSON. It's already extracted the zip codes and the code just adds the zip codes to the array. . This line:
var sv = JSON.stringify(data).match(new RegExp(name+'([\\S\\s]*?}][\\S\\s]*?}])'))[1].match(/zipCodes":\[(.*?)\]/g), r = [];
is what grabs the zip codes, it gets something like:
["zipCodes":["768019","768020"]"]
The next line:
item.match(/\d+/g)
will grab the numbers outputting something like:
["768019", "768020"]
The loop just adds the zip-codes to another array
With looping
You're better off looping through the JSON:
var myData = {}, // Your data
zips = [];
myData.countries.forEach(function(i) {
if (i.name === 'India') {
i.states.forEach(function(j) {
j.cities.forEach(function(l) {
l.zipCodes.forEach(function(m) {
zips.push(m);
});
});
});
}
});
//use "zips" array
PERFORMANCE AND SPEED TESTS
After testing copying an array about 500MB (half a gig) took about 30 seconds. That's a lot. Considering an extremely large JSON would be about ~5MB, looping through a little over 5MB of JSON takes about 0.14 seconds. You should never worry about speed.
Here's my "trick" for avoiding explicit iteration. Let JSON.parse or JSON.stringify do the work for you. If your JSON is in string form, try this:
var array = [];
JSON.parse(jsonString, function (key, value) {
if (key === "zipCodes") {
array = array.concat(value);
}
return value;
});
console.log(array); // all your zipCodes
Suppose your Json is like
countries =[
{
name:'India',
states:[{
name:'Orissa',
cities:[{
name:'Sambalpur',
zipCodes:768019768020
}]
},{
name:'mumbai',
cities:[{
name:'rea',
zipCodes:324243
}]
}]
}
]
So now we use MAP it will give you ZipCode of every cities
countries.map(function(s){
s.states.map(function(c){
c.cities.map(function(z){
console.log(z.zipCodes)
})
})
})
OR
If you use return statement then it will give you 2 array with two zip code as per over JSON
var finalOP = countries.map(function(s){
var Stalist = s.states.map(function(c){
var zip = c.cities.map(function(z){
return z.zipCodes
})
return zip
})
return Stalist
})
console.log(finalOP)

Javascript: How to parse a json array without knowing the key name?

I want to parse the following json:
{"key_410441":{"hashId":"hash123","tube_id":"4accdefk31"}}
Where key_410441 is the entry's name representing the object's value, and the following array is the object's data.
How can I retrieve it's value?
function defined(json) {
for (var i in json) {
var objId = json[i]. ????
}
}
Like Robo Robok said, use Object.keys(object)
if your json look like {"key_410441":{"hashId":"hash123","tube_id":"4accdefk31"}}
function defined(json) {
var hashId = json[Object.keys(json)[0]].hashId
var tube_id = json[Object.keys(json)[0]].tube_id
}
}
you can use shortcut json[Object.keys(json)] because you have olny one object
key_410441
Object keys are returned in form of an array by Object.keys(object)
I suppose you are using jquery and ajax to get a json from an external file. Then the piece of code would be:-
$.getJSON("aa.json", function(data) {
var obj = Object.keys(data),
json = data[obj];
for(var s in json) {
console.log(json[s]);
}
});

Each jquery get values

Here I have this code jquery:
JSON.stringify($("#vrsta_rada").select2("data"));
and I get this JSON file:
"[{"id":2,"text":"setva/zasad"},{"id":6,"text":"orezivanje"},{"id":8,"text":"skladistenje"}]"
How I can use .each function to get this string: data[0].text, data[1].text ...
so to get string from JSON above: setva/zasad, orezivanje, skladistenje
?
I'm not sure why you are stringifying the data if you want to manipulate it. So this will work:
var data = $("#vrsta_rada").select2("data");
$.each(data, function(key, value) {
var text = data[key].text
//or
var text = value.text
});
Is this what you are looking for? That will iterate through the list. I prefer to use data[key] because you can then manipulate the data and it will change the original whereas value only makes a copy.
Try
$.each(data, function(index, value) {
alert(value.text)
});

Categories