Get JSON stringify value - javascript

I have JSON stringify data like this :
[{"availability_id":"109465","date":"2017-02-21","price":"430000"},{"availability_id":"109466","date":"2017-02-22","price":"430000"},{"availability_id":"109467","date":"2017-02-23","price":"430000"}]
I want to get only price value of that data. I have tried this way but it doesn't work.
var stringify = JSON.stringify(values);
for(var i = 0; i < stringify.length; i++)
{
alert(stringify[i]['price']);
}
How could I to do that ?

This code will only fetch the price details.
var obj = '[{"availability_id":"109465","date":"2017-02-21","price":"430000"},{"availability_id":"109466","date":"2017-02-22","price":"430000"},{"availability_id":"109467","date":"2017-02-23","price":"430000"}]';
var stringify = JSON.parse(obj);
for (var i = 0; i < stringify.length; i++) {
console.log(stringify[i]['price']);
}

Observation :
If you want to parse the array of objects to get the property value you have to convert in into JSON object first.
DEMO
var jsonStringify = '[{"availability_id":"109465","date":"2017-02-21","price":"430000"},{"availability_id":"109466","date":"2017-02-22","price":"430000"},{"availability_id":"109467","date":"2017-02-23","price":"430000"}]';
var jsonObj = JSON.parse(jsonStringify);
for(var i = 0; i < jsonObj.length; i++)
{
alert(jsonObj[i]['price']);
}

you will geting a stringified object like this
var obj='[{"availability_id":"109465","date":"2017-02-21","price":"430000"},
{"availability_id":"109466","date":"2017-02-22","price":"430000"},
{"availability_id":"109467","date":"2017-02-23","price":"430000"}]';
parse your obj using JSON.parse(object)
then apply this loop ad let me know it get any error
lie this
var parseObject = JSON.parse(object);

instead of using stringify before selecting the data you should use your loop directly on the values array.
For example :
var priceArray = array();
values.forEach (data) {
alert(data['price'];
priceArray.push(data['price']);
}
stringify = JSON.stringify(values);
stringifiedPriceArray = JsON.stringify(priceArray);
Once stringified, you can't reach the data in your array

Related

How to find JSON data at specific index

I want to show only the country name like India,Srilanka etc.
{"result":1,"countries":[
{"country_id":"1","country_name":"Afghanistan"},
{"country_id":"2","country_name":"Albania"},
{"country_id":"3","country_name":"Algeria"},
{"country_id":"4","country_name":"American Samoa"},
{"country_id":"5","country_name":"Andorra"},
{"country_id":"6","country_name":"Angola"},
{"country_id":"7","country_name":"Anguilla"}
]
}
Below I have created JSON object same as yours:
var text = '{"result":1,"countries":[' +
'{"country_id":"1","country_name":"Afghanistan"},' +
'{"country_id":"2","country_name":"Albania"},' +
'{"country_id":"3","country_name":"Algeria"}'+
']}';
var obj = JSON.parse(text);
you can loop through JSON object and get each property value as below:
for(i = 0; i < obj.countries.length ; i++)
{
console.log(obj.countries[i].country_name);
}
Hope This Will Help!
why no iterate the objects and pull that data into a separate array? for example:
[[{"country_id":"1","country_name":"Afghanistan"},{"country_id":"2","country_name":"Albania"},{"country_id":"3","country_name":"Algeria"},{"country_id":"4","country_name":"American Samoa"},{"country_id":"5","country_name":"Andorra"},{"country_id":"6","country_name":"Angola"},{"country_id":"7","country_name":"Anguilla"}]]
.forEach(function(element) {
console.log(element.country_name);
});

Append JSON elements in Ember

I am having an array with some of values (i.e., [1,2,3,4,5]), now i have to convert this array elements into JSON format.
I tries this one,
var Jsondata = {};
for (i = 0; i < Response.get('firstname').length; i++) {
Jsondata.push({
name : Response.get('firstname')[i]
});
}
Ember.Logger.debug(Jsondata );
but it shows some error :
carousel.js:575 Uncaught TypeError: Jsondata.push is not a function(…)
how to append json elements in ember?
Can you please try like this.
var Jsondata = [];
for (i = 0; i < Response.get('firstname').length; i++) {
Jsonvalue = {
name : Response.get('firstname')[i]
}
Jsondata.push(Jsonvalue);
}
Your Jsondata is a hash instead of an array. If you change it to an array your code should work. Your issue is unrelated to Ember

Looping through dynamic JSON data using javascript

I am trying to display JSON data but the key value is dynamic it varies from one POST request to another my data hierarchy is as shown in diagram:
This is the part of the code I am running,Can anyone suggest me how to display JSON data where key showed in redbox gonna change for every POST request
$.ajax({
type: "POST",
url: "/",
dataType:'json',
data : { 'perfid': valueOne, 'hostname': $("#host").val(), 'iteration': valueThree},
success: function(data) {
$('#img1').hide();
var k = data[$("#host").val()].iscsi_lif.result.sectoutput.sect.length;
for(var i = 0; i < k; i++) {
var obj = k[i];
console.log(obj);
var iscsi = parseInt(data[$("#host").val()].iscsi_lif.result.sectoutput.sect.obj.avg_latency);
console.log(iscsi);
}
While running above snippet I am getting following error message :
data[$(....).val(...)].iscsi_lif.result.sectoutput.sect is undefined
You can use a "for in" loop to iterate over the keys of an object without having to specify the key names.
for( var key in myObject){
myValue = myObject[key];
// key will be your dynamically created keyname
}
So your code could be similar to the following:
...
success: function(data) {
$('#img1').hide();
var obj = data[$("#host").val()].iscsi_lif.result.sectoutput.sect;
for(var key in obj) {
if(obj.hasOwnProperty(key)){
var iscsi = parseInt(obj[key].avg_latency);
console.log(iscsi);
}
}
}
Solution Suggestion:
for (var key in object) {
if (object.hasOwnProperty(key)) {
var element = object[key];
}
}
Yet, in your situation, maybe you'll have to do this multiple times, so I would try to extract a generic function to do this and "normalize" the processing result to an expected format that wouldn't change.
The function will only run when the expected keys exist and since the forin loop uses the object keys, every object is processed dynamically.
This should work:
var k = data[$("#host").val()].iscsi_lif.result.sectoutput.sect;
for (var i = 0; i < k.length; i++) {
var obj = k[i];
console.log(obj);
var iscsi = parseInt(data[$("#host").val()].iscsi_lif.result.sectoutput.sect[obj].avg_latency);
console.log(iscsi);
}
The variable should be put inside brackets.
Also, it seemed to me that k was simply defined as length of an array, I removed that and put it to the for loop.
Since you have obj defined as varible you should use [], so it will be [obj], e.g :
var iscsi = parseInt(data[$("#host").val()].iscsi_lif.result.sectoutput.sect[obj].avg_latency);
Hope this helps.

how to get values from json with unknown ammount of given elements

Given this json as example:
[
{"offspring0":"John"},
{"offspring1":"Anna"},
{"offspring2":"Peter"}
]
I can know how many offspring are there with:
offspringCount = (jsonString.match(/offspring/g) || []).length; //jsonString is the json above
This would return 3. Now, how can i get the value of all those offsprings? I have tried:
json = JSON.parse(jsonString);
alert(json[0].offspring[0]);
But this throws Uncaught TypeError: Cannot read property '0' of undefined because offspring is not an array.
I also tried:
alert(json[0]."offspring0");
But getting Uncaught SyntaxError: Unexpected string
My intention is to loop through all the offspring[number] and get the values, was expecting something like this:
for(x=0; x<offspringCount; x++){
alert(json[0].offspring[x]);
}
Note i do not handle the making of the JSON, i only request it to a server.
Try this:
var jsonString = '[{"offspring0":"John"},{"offspring1":"Anna"},{"offspring2":"Peter"}]';
var array = JSON.parse(jsonString);
var offsprings = [];
for (var i=0; i<array.length; ++i) {
for (var key in array[i]) {
if (key.match(/^offspring[0-9]+$/)) {
offsprings.push(array[i][key]);
}
}
}
document.getElementById('output').innerHTML = JSON.stringify(offsprings);
<div id="output"></div>
I thing this code may help you
json = JSON.parse(jsonString);
alert(json[0]['offspring0']);
this means, when you need to loop around your array , you need to do something like this:
for(var index = 0; index < json.length; index++) {
alert(json[index]['offspring' + index]);
}

attempting to convert String data into numerical data, the drop the data into an array of arrays (Json)

I have this:
(65.94647177615738, 87.890625)(47.040182144806664, 90)(45.089035564831036, 122.34375)
I'm attempting to get the output to look like this:
"coords": [[65.94647177615738, 87.890625],[47.040182144806664, 90],[45.089035564831036, 122.34375]]
Any Idea?
The first result comes back to me as a string, so when i try to assign the first object to an array, the console shows me this:
array is: "(65.94647177615738, 87.890625)(47.040182144806664, 90)(45.089035564831036, 122.34375)"
var str = "(65.94647177615738, 87.890625)(47.040182144806664, 90)(45.089035564831036, 122.34375)";
str = str.slice(1,-1); // remove outermost parentheses
var arrCoord = str.split(')(');
for (var i=0; i<arrCoord.length; i++) {
var tarr = arrCoord[i].split(", ");
for (var j=0; j<tarr.length; j++) {
tarr[j] = parseFloat(tarr[j]);
}
arrCoord[i] = tarr;
}
// arrCoord is now populated with arrays of numbers
Decided to sort of play code golf. Assuming:
var sample = '(65.94647177615738, 87.890625)(47.040182144806664, 90)(45.089035564831036, 122.34375)';
Then:
var coords = sample
.split(/\(([^)]+)\)/)
.filter(function(v){return v!=""})
.map(function(v){return v.split(/[^0-9\.]+/)})

Categories

Resources