How to properly use JSON.parse? - javascript

I'm receiving a string with php and then parsing it:
String saved in db:
{"totale_casi":825,"terapia_intensiva":24,"ricoverati_con_sintomi":122,"totale_ospedalizzati":146,"isolamento_domiciliare":598,"totale_positivi":744,"dimessi_guariti":40,"deceduti":41,"tamponi":6477}, {"totale_casi"235,"terapia_intensiva":123,"ricoverati_con_sintomi":154,"totale_ospedalizzati":344,"isolamento_domiciliare":654,"totale_positivi":786,"dimessi_guariti":988,"deceduti":675,"tamponi":2324}
Then I do
var myJson = '<?php echo $dataCustom; ?>';
This is how It prints on js
var myJson = '{"totale_casi":825,"terapia_intensiva":24,"ricoverati_con_sintomi":122,"totale_ospedalizzati":146,"isolamento_domiciliare":598,"totale_positivi":744,"dimessi_guariti":40,"deceduti":41,"tamponi":6477}, {"totale_casi"235,"terapia_intensiva":123,"ricoverati_con_sintomi":154,"totale_ospedalizzati":344,"isolamento_domiciliare":654,"totale_positivi":786,"dimessi_guariti":988,"deceduti":675,"tamponi":2324}';
How to read a property?
Tried
var myJson = '<?php echo $dataCustom; ?>';
var customJsonData = JSON.parse(myJson);
I am trying to:
for(var d = 0; d < customJsonData.length; ++d) {
console.log(customJsonData[d]totale_positivi);
}
UPDATE
This is how I am constructing the json
var saveJsondata = {
"totale_casi": totCasiRegione,
"terapia_intensiva": totTerapiaRegione,
"ricoverati_con_sintomi": totSintomiRegione,
"totale_ospedalizzati": totOspedalizzatiRegione,
"isolamento_domiciliare": totDomiciliariRegione,
"totale_positivi": totPositiviRegione,
"dimessi_guariti": totGuaritiRegione,
"deceduti": totDecedutiRegione,
"tamponi": totTamponiRegione
};
Then sending that to db via ajax and Adding | in order to have something that I can use to separate the objects later. I am saving saveJsondata to a field called jsonBlock
Then in php I do:
$dataSavedBlocks = get_user_meta( $user_id, 'jsonBlock');
$dataCustom = $dataSavedBlocks[0];
$dataCustom = str_replace('|', '', $dataCustom);
Finally in js:
var myJson = '<?php echo $dataCustom; ?>';
Output of that is:
var myJson = {"totale_casi":825,"terapia_intensiva":24,"ricoverati_con_sintomi":122,"totale_ospedalizzati":146,"isolamento_domiciliare":598,"totale_positivi":744,"dimessi_guariti":40,"deceduti":41,"tamponi":6477} ,{"totale_casi":47348,"terapia_intensiva":1362,"ricoverati_con_sintomi":11726,"totale_ospedalizzati":13088,"isolamento_domiciliare":12935,"totale_positivi":26023,"dimessi_guariti":13020,"deceduti":8305,"tamponi":133588} ;
Now I need to loop and get each individual value

You don't need to use the loop... just try console.log(customJsonData.totale_positivi). JSON properties become object attributes when parsed. Hence JavaScript Object Notation 8^D

Actually it is not an Array. If you want to iterate, use object keys.
var myJson = '{"totale_casi":825,"terapia_intensiva":24,"ricoverati_con_sintomi":122,"totale_ospedalizzati":146,"isolamento_domiciliare":598,"totale_positivi":744,"dimessi_guariti":40,"deceduti":41,"tamponi":6477} ';
var customJsonData = JSON.parse(myJson);
Object.keys(customJsonData).forEach(key=>{
console.log(customJsonData[key]);
})
If you want a single value:
var myJson = '{"totale_casi":825,"terapia_intensiva":24,"ricoverati_con_sintomi":122,"totale_ospedalizzati":146,"isolamento_domiciliare":598,"totale_positivi":744,"dimessi_guariti":40,"deceduti":41,"tamponi":6477} ';
var customJsonData = JSON.parse(myJson);
console.log(customJsonData.terapia_intensiva)
If you have an array of objects :
var myJson = '[{"totale_casi":825,"terapia_intensiva":24,"ricoverati_con_sintomi":122,"totale_ospedalizzati":146,"isolamento_domiciliare":598,"totale_positivi":744,"dimessi_guariti":40,"deceduti":41,"tamponi":6477},{"totale_casi":826,"terapia_intensiva":24,"ricoverati_con_sintomi":122,"totale_ospedalizzati":146,"isolamento_domiciliare":598,"totale_positivi":744,"dimessi_guariti":40,"deceduti":41,"tamponi":6477},{"totale_casi":827,"terapia_intensiva":24,"ricoverati_con_sintomi":122,"totale_ospedalizzati":146,"isolamento_domiciliare":598,"totale_positivi":744,"dimessi_guariti":40,"deceduti":41,"tamponi":6477}]';
var customJsonData = JSON.parse(myJson);
customJsonData.forEach(data=>{
console.log(data.totale_casi);
})

This is how I resolved it:
var myJson = '<?php echo $dataCustom; ?>';
var customJsonData = JSON.parse("["+myJson+"]");
Now that we have a valid json, we can loop and iterate with each obj:
for(var d = 0; d < customJsonData.length; ++d) {
console.log(customJsonData[d].totale_casi);
}

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;
}
}

Create an associative array in jquery using php array

I need to create an assosiative array in jQuery from PHP.
Here is my script so far. selectedStoresDict is json encoded array with values ["Lahore", "Islamabad"]
var selectedStores = <?php echo $selectedStoresDict; ?>;
var data = {};
for( i = 0 ; i <= selectedStores.length; i++) {
data['id'] = i;
data['text'] = selectedStores[i];
}
console.log(data, "Hello, world!");
However my console is showing that its not an array. I want something like this:
[{ id: 1, text: 'Lahore' }, { id: 2, text: 'Islamabad' }]
I think this should be a JS question instead of a PHP one, but here you have. You were almost there:
var selectedStores = <?php echo $selectedStoresDict; ?>;
var data = [];
for( i = 1 ; i <= selectedStores.length; i++) {
data.push({
id: i,
text: selectedStores[i]
});
}
console.log(data, "Hello, world!");
An array in JS is represented with [], so you need to initialize it like that, then just push the info (in this case, and object with keys and values). Also for ids starting with 1, you must initialize i = 1.
No need to loop thru.
Just json_encode the array
<?php
$selectedStoresDict[] = array("id"=>1,"text"=>"Lahore");
$selectedStoresDict[] = array("id"=>2,"text"=>"Islamabad");
?>
<script>
console.log('<?php echo json_encode($selectedStoresDict); ?>');
</script>

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.

How to get multidimensional array data using java script and php

I have a multidimensional array in php, and i want to get its data from javascript but i didn't work
here my code in php
$managername = $_SESSION['managername'];
$sqls = "select s.*,m.* from rm_allowedmanagers m inner join rm_services s on s.srvid = m.srvid where m.managername = '$managername' ";
$sql = mysql_query($sqls);
$newservices = array();
while($row = mysql_fetch_array($sql))
{
$nsrvid = $row['srvid'];
$nsrvname = $row['srvname'];
$nunitprice = $row['unitprice'];
$nunitpricetax = $row['unitpricetax'];
$ntotal = $nunitprice + $nunitpricetax;
$newservice = array($nsrvid, $nsrvname , $ntotal);
array_push ($newservices, $newservice);
}
and here my java script code
<script>
function changeserviceprice(id)
{
var newservice = $("#newservice").val();
var data = '<?= $newservices ?>';
var asd = data;
var asd2 = data[0][0];
$("#qq4").val(asd);
$("#qq5").val(asd2);
}
</script>
PHP code i think it is work fine, and i think the error is in javascript function.
when i try to print the data using javascript it print the "Array" word when i print the whole row "array", but
it print "a" character when i try to print the first element in the first array!!
try encoding the $newservices array:
var data = <?php echo json_encode($newservices); ?>;

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