Convert Array to objects for Jsondata objects in js - javascript

Convert Array-String to Object with Javascript or jQuery
here is my array
data=["{X:7,Y:12.5}", "{X:8,Y:15}", "{X:9,Y:12.5}"]
expected output is object
data=[{X:7,Y:12.5},{X:8,Y:15},{X:9,Y:12.5}]
how to do that?

You can try something like this:
var data=["{X:7,Y:12.5}", "{X:8,Y:15}", "{X:9,Y:12.5}"];
data = data.map(function(item){
item = item.replace(/{/g, "{\"");
item = item.replace(/}/g, "\"}");
item = item.replace(/:/g, "\":\"");
item = item.replace(/,/g, "\",\"");
return JSON.parse(item);
})
console.log(data)

Try this:
data = ["{X:7,Y:12.5}", "{X:8,Y:15}", "{X:9,Y:12.5}"];
data = data.join(',');
data = data.replace(/X/g,'"X"');
data = data.replace(/Y/g,'"Y"');
data = JSON.parse("["+data+"]");
Just convert array to string and do clean up that can be parsed to json.

Simple solution is to replace the X and Y with "X" & "Y". In order to create a string key that can be parse as JSON.
data=["{X:7,Y:12.5}", "{X:8,Y:15}", "{X:9,Y:12.5}"]
for(var i in data){
tmp = data[i].replace("X",'"X"').replace('Y','"Y"')
data[i] = JSON.parse(tmp)
}
Enjoy.

var reg = /[^{,]+?(?=:)/g;
var data = ["{X:7,Y:12.5}", "{X:8,Y:15}", "{X:9,Y:12.5}"];
data = data.map(function(item){
return JSON.parse(item.replace(reg, "\"$&\""));
});

Related

Get JSON stringify value

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

How could I create a JSON array in a javascript loop

I would like to create a javascript json array. At the and I would Like to have something like this :
var requestData= {"uris":["SampleName1", "SampleName2", "SampleName3"],"limit":100 };
The names are stored in another variable called result.results.bindings I think my for loop should be like this :
for(binding in result.results.bindings){
// binding holds SampleName1,sampleName2.. etc
}
So how could I create the array that I mentioned above?
Do you mean something like this?
var data = [];
for(binding in result.results.bindings)
data.push(binding);
var returnObject = {uris: data, limit: 100};
I do not know the structure of your data in result.results.bindings, but with the for loop you are looping over the keys of the object / array.
If you want to loop over the values and the data-source is an array you can use this:
var data = [];
result.results.bindings.forEach(function(value) {
data.push(value);
});
var returnObject = {uris: data, limit: 100};
var requestData = {};
var uris = [];
for (binding in result.results.bindings){
uris.push(binding);
}
requestData.uris = uris;
Edited as suggestion from #BenM:
var requestData = {};
requestData.uris = result.results.bindings;
I think for-in loop is not a good practice with array, It's good with object
for(var i = 0, uris = []; i < result.results.bindings.length; i++)
uris.push(result.results.bindings[i]);
var returnObject = {"uris": uris, "limit": 100};
console.log(returnObject);
var data = [];
result.results.bindings.forEach(function(value) {
eval('data.' + value + ' = ' + value);
});
// then access your variables like
alert(data.SampleName1);

Converting JSON to specific string format

I get the following json data from server.
{"visits":[{"City":6,"Count":5},{"City":16,"Count":1},{"City":23,"Count":1},{"City":34,"Count":1}]}
and i need to convert it to following format:
{"1":"82700","2":"26480","3":"31530","4":"22820","5":"15550","6":"205790"}
I have the following code but not working out:
var cities = "{";
for (var key in data.visits) {
var val = data.visits[key];
//Now you have your key and value which you
//can add to a collection that your plugin uses
var obj = {};
obj[val.City] = '' + val.Count;
var code = '' + val.City;
var count = '' + val.Count;
cities += code + ':' + count + ',';
}
cities += "}";
I need the integers in string representation and need to get rid of the final , .
How can i fix this?
Try this
var data = {"visits":[{"City":6,"Count":5},{"City":16,"Count":1},{"City":23,"Count":1},{"City":34,"Count":1}]};
var result = {};
for (var i = 0; i < data.visits.length; i++) {
result[data.visits[i].City] = String(data.visits[i].Count);
}
Example
Keys in object always converts to string you don't need convert it to string manually. If you need convert all object to JSON string you can use JSON.stringify(result);
How I understood you want to create new json with given json.you can parse it,run with cycle on it,and create a new json whatever kind of you want.
here is a link which can help you.
http://www.w3docs.com/learn-javascript/working-with-json.html

Access to a certain part of JSON data with jQuery

So i have this JSON:
{
"id_u":"1",
"nombre_usuario":"JESUS",
"apellido_paterno_usuario":"DIAZ"
}
I just want to access to the fields names
id_u,_nombre_usuario,apellido_paterno_usuario
And then, create an array with that info.
How can i do that?
Thanks guys
Do this way :
var keyValuePair = {
"id_u":"1",
"nombre_usuario":"JESUS",
"apellido_paterno_usuario":"DIAZ"
};
var arr =new Array();
for (key in keyValuePair){
arr.push(key); // for keys
// arr.push(keyValuePair[key]); // for values
}
Use .each() to parse JSON.
Try this:
var keyArray = [];
var a = {
"id_u":"1",
"nombre_usuario":"JESUS",
"apellido_paterno_usuario":"DIAZ"
};
$.each(a,function(i,v){
keyArray.push(i); // i is json key and v is json value.
});
console.log(keyArray);
DEMO
Object.keys(jsonObject) is enough.

Push to array a key name taken from variable

I have an array:
var pages = new Array();
I want to push my pages data to this array like this:
$('li.page').each(function () {
var datatype = $(this).attr('data-type');
var info = $(this).attr('data-info');
pages_order.push({datatype:info});
});
but this code doesn't replace datatype as variable, just puts datatype string as a key.
How do I make it place there actual string value as a key name?
I finally saw what you were trying to do:
var pages = new Array();
$('li.page').each(function () {
var datatype = $(this).attr('data-type');
var info = $(this).attr('data-info');
var temp = {};
temp[datatype] = info;
pages_order.push(temp);
});
$('li.page').each(function () {
//get type and info, then setup an object to push onto the array
var datatype = $(this).attr('data-type'),
info = $(this).attr('data-info'),
obj = {};
//now set the index and the value for the object
obj[datatype] = info;
pages_order.push(obj);
});
Notice that you can put a comma between variable declarations rather than reusing the var keyword.
It looks like you just want to store two pieces of information for each page. You can do that by pushing an array instead of an object:
pages_order.push([datatype, info]);
You have to use datatype in a context where it will be evaluated.
Like so.
var pages = [];
$('li.page').each(function () {
var datatype = $(this).attr('data-type'),
info = $(this).attr('data-info'),
record = {};
record[datatype] = info;
pages_order.push(record);
});
You only need one var it can be followed by multiple assignments that are separated by ,.
No need to use new Array just use the array literal []
You may add below single line to push value with key:
pages_order.yourkey = value;

Categories

Resources