Convert Json Object to Array in JS - javascript

I convert Array in php by json_encode and send to JS.
I want convert this json:
[{"category_id":4},{"category_id":2},{"category_id":3}]
to:
['3','2','4']

You should use map method.
let array=[{"category_id":4},{"category_id":2},{"category_id":3}]
array=array.map(function(item){
return item.category_id.toString();
});
console.log(array);

try this code :
var myObj = [{"category_id":4},{"category_id":2},{"category_id":3}]
var yourArray = myObj.map(function(value, index) {return value.category_id;})
I think this should resolve your issue.

var data = [{"category_id":4},{"category_id":2},{"category_id":3}];
var id = [];
for(var i in data)
{
id.push(data[i].category_id);
}
console.log(id);

try this
var a = [{"category_id":4},{"category_id":2},{"category_id":3}];
var b=[];
for(let i of a){
b.push(i.category_id);
}
console.log(b);

let array=[{"category_id":4},{"category_id":2},{"category_id":3}]
array=array.map(function(item){
return item.category_id.toString();
});
console.log(array);
I json Pass In php to JS with variable $category
bu in JS var array= <?php echo $category; ?>
error : Uncaught SyntaxError: Unexpected identifier

Related

Json in javascript

i am getting a problem to get json string creating in javascript,
in console log getting pure json string
like
[{"elementId":"selectProduct","elemnetValue":"Y"},{"elementId":"productId","elemnetValue":"415"}]
but when i am storing the output of the json in variable
it change like
[{\"elementId\":\"selectProduct\",\"elemnetValue\":\"Y\"},{\"elementId\":\"productId\",\"elemnetValue\":\"415
"}]
so it can't parse by
JSON.parse(jsonString);
You can use JSON.stringify to get a "parseable" string..
like
var str = JSON.stringify([{"elementId":"selectProduct","elemnetValue":"Y"},{"elementId":"productId","elemnetValue":"415"}]);
var json = JSON.parse(str);
i am done with following code :
var jsonString;
$("#submit").click(function() {
var _intrimForm={
};
var json=[];
var len = document.getElementById("myForm").elements.length;
for(var i=0;i<len;i++){
var _id =document.getElementById("myForm").elements[i].id;
var value = document.getElementById("myForm").elements[i].value;
_intrimForm={
'elementId':_id,
'elemnetValue':value
};
json.push(_intrimForm);
}
console.log(json);
jsonString = JSON.stringify(json);
console.log(jsonString);
readJsonFormElement();
});
function readJsonFormElement()
{
var jsonInterim = new Array();
jsonInterim=JSON.parse(jsonString);
for(var i=0;i<jsonInterim.length;i++)
{
var eId=jsonInterim[i].elementId;
var eValue=jsonInterim[i].elemnetValue;
}
}

Convert Array to objects for Jsondata objects in js

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, "\"$&\""));
});

How to fill javascript array from ajax data result

I have scripts like this.
javascript
$.ajax({
url : "load_data_person.php",
dataType:"json",
success:data_person(arrData)
});
function data_person(info_person){
var attr = [];
var len = [];
for(j=0;j<info_person.length;j++){
attr.push(info_person[j][0]);
len.push(info_person[j][1]);
}
return [attr, len];
}
How can I insert data to variable info_person like this:
info_person = [['fname',20],['lname',15],['addr',50]];
so I can get each value of attr and len?
Here is the script for data_person.php
<?php
$qStrPerson = mysql_query("SELECT atribut, len FROM tb_person ORDER BY fname ASC");
$arrFullPerson = array();
while($rStrPerson = mysql_fetch_array($qStrPerson)){
$arrFullPerson[] = array($rStrPerson[atribut],$rStrPerson[len]);
}
echo json_encode($arrFullPerson);
// it will return like this : Array 0 : ['fname', 20], Array 1 : ['lname',15], Array 2 : ['addr',50]];
?>
Thank you for your help.
You can use simple jquery to convert the JSON to Javascript array
var array = JSON.parse(your json string);
You can just format the array as you wanted in the server side and then echo it. While receiving the ajax response, you can simply
var info_person = json.parse(arData);
to convert the json-encoded value into javascript array.

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.

Convert js Array() to JSon object for use with JQuery .ajax

in my app i need to send an javascript Array object to php script via ajax post. Something like this:
var saveData = Array();
saveData["a"] = 2;
saveData["c"] = 1;
alert(saveData);
$.ajax({
type: "POST",
url: "salvaPreventivo.php",
data:saveData,
async:true
});
Array's indexes are strings and not int, so for this reason something like saveData.join('&') doesn't work.
Ideas?
Thanks in advance
Don't make it an Array if it is not an Array, make it an object:
var saveData = {};
saveData.a = 2;
saveData.c = 1;
// equivalent to...
var saveData = {a: 2, c: 1}
// equivalent to....
var saveData = {};
saveData['a'] = 2;
saveData['c'] = 1;
Doing it the way you are doing it with Arrays is just taking advantage of Javascript's treatment of Arrays and not really the right way of doing it.
If the array is already defined, you can create a json object by looping through the elements of the array which you can then post to the server, but if you are creating the array as for the case above, just create a json object instead as sugested by Paolo Bergantino
var saveData = Array();
saveData["a"] = 2;
saveData["c"] = 1;
//creating a json object
var jObject={};
for(i in saveData)
{
jObject[i] = saveData[i];
}
//Stringify this object and send it to the server
jObject= YAHOO.lang.JSON.stringify(jObject);
$.ajax({
type:'post',
cache:false,
url:"salvaPreventivo.php",
data:{jObject: jObject}
});
// reading the data at the server
<?php
$data = json_decode($_POST['jObject'], true);
print_r($data);
?>
//for jObject= YAHOO.lang.JSON.stringify(jObject); to work,
//include the follwing files
//<!-- Dependencies -->
//<script src="http://yui.yahooapis.com/2.9.0/build/yahoo/yahoo-min.js"></script>
//<!-- Source file -->
//<script src="http://yui.yahooapis.com/2.9.0/build/json/json-min.js"></script>
Hope this helps
You can iterate the key/value pairs of the saveData object to build an array of the pairs, then use join("&") on the resulting array:
var a = [];
for (key in saveData) {
a.push(key+"="+saveData[key]);
}
var serialized = a.join("&") // a=2&c=1
There is actuly a difference between array object and JSON object. Instead of creating array object and converting it into a json object(with JSON.stringify(arr)) you can do this:
var sels = //Here is your array of SELECTs
var json = { };
for(var i = 0, l = sels.length; i < l; i++) {
json[sels[i].id] = sels[i].value;
}
There is no need of converting it into JSON because its already a json object.
To view the same use json.toSource();
When using the data on the server, your characters can reach with the addition of slashes eg
if string = {"hello"}
comes as string = {\ "hello \"}
to solve the following function can be used later to use json decode.
<?php
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
$array = $_POST['jObject'];
$array = stripslashes_deep($array);
$data = json_decode($array, true);
print_r($data);
?>

Categories

Resources