Json decode in javascript - php

i have encoded my required data in the json object ,but i want to decode the json object into a javscript array, my json encoded object is :
{"product_id":"62","product_quantity":"65"}
however i want to use this json in my java script and want it to be available to a java script array
so if i do :
var arr = new Array()
arr = <?php json_decode('$json_object',TRUE); ?>;
however when i check my page source i get null i.e arr =
how can i assign my json object converted to array to java script array ?
further how to access the json objects from java script array ?

json_decode returns a PHP data structure. If you want to serialise that to a JavaScript data structure you have to pass it through json_encode (and then actually echo the string that it returns).
Note that json_encode outputs a JavaScript data structure that is safe for injecting into a <script> element in an HTML document. Not all JSON is safe to do that with (PHP adds additional escape sequences, and will transform plain strings, numbers, null values, etc (which aren't legal JSON on their own).
Note that there is also no point in creating a new array and assigning it to arr if you are going to immediately assign something else to arr.
Also note that '$json_object' will give you a string starting with the $ character and then the name of the variable. Single quoted string in PHP are not interpolated.
var arr;
arr = <?php echo json_encode(json_decode($json_object,TRUE)); ?>;
Also note that this JSON:
{"product_id":"62","product_quantity":"65"}
Will transform in to a PHP associative array or a JavaScript object (which is not an array).
So given this PHP:
<?php
$json_object = '{"product_id":"62","product_quantity":"65"}';
?>
<script>
var arr;
arr = <?php echo json_encode(json_decode($json_object,TRUE)); ?>;
alert(arr.product_id);
</script>
You get this output:
<script>
var arr;
arr = {"product_id":"62","product_quantity":"65"};
alert(arr.product_id);
</script>
Which alerts 62 when run.

You could push the JSON objects into javascript array and iterate through the array, selecting the appropriate fields you need.
Fixed it..
var json = {"product_id":"62","product_quantity":"65"};
var array = new Array();
array.push(json);
for(var i = 0; i < array.length; i++){
console.log(array[i].product_id)
}

Okay so to start off :
the json string generated in PHP can be used in Javascript as an Object. If you declare the variable as an array to start with then it might conflict.
anyway this should work :
<?php
$error_fields_structure = array(
'product_id' => 4531
,'main_product_quantity' => 2
);
$json_object = json_encode($error_fields_structure);
?>
<html>
<head>
<script>
var jsonstring = <?php echo (isset($json_object) ? $json_object : 'nothing here'); ?>
for( var i in jsonstring ){
alert( i +' == ' +jsonstring[i] );
}
</script>
</head>
<body>
</body>
</html>

Related

How to read Json_encoded php array from jquery?

I have a php array like this one :
Array
(
[0] => banana, peach, cherry
[1] => strawberry, apple, lime
)
I pass it to Jquery using json_encode($myArray)
In Jquery I receive my array like this : ["banana, peach, cherry","strawberry, apple, lime"]
Now I wanna extract each value : "banana, peach, cherry" & "strawberry, apple, lime"
When I try to use this :
$.each(data, function(key, value){
alert(value);
});
it alerts me each chars : [ " b a n a n................ etc instead each value.
Do you know why ?
EDIT :
This is how I receive my data from php :
$.post('ajax/fruits.php', function(data) {
var obj = $.parseJSON(data);
var chunks = obj['chunks'] // gives me : ["banana, peach, cherry","strawberry, apple, lime"]
if (obj['error']==0) {
mix_fruits(chunks); // a function that should extract each value
}
});
You don't show how you are passing and receiving the data, but somewhere in the process you are making a mistake.
It is evident from the description that data is a string, not an array as it should have been based on the PHP variable. And since the string begins with the characters that make up the JSON representation of your data, this means the JSON is being wrapped into a string instead of parsed as a JavaScript literal.
Assuming that passing/receiving is not done through an AJAX request (in which case jQuery would almost certainly parse the data automatically) I 'm guessing that you are doing this:
var data = '<?php echo json_encode($data); ?>';
while you should instead be doing this:
var data = <?php echo json_encode($data); ?>; // no quotes!
You need to parse the JSON object before you can use it,
var jsonObj = jQuery.parseJSON(data);
then to loop through each item use this,
for(var key in jsonObj)
{
curr = jsonObj[key];
}
And if you want to use non-jquery one,
Parse JSON in JavaScript?

Create a Javascript array from a PHP array

I am having trouble converting from a PHP array to a Javascript array and then accessing the value. I have tried JSON encoding and decoding.
PHP:
$simpleArray= [];
$childProducts = Mage::getModel('catalog/product_type_configurable')
->getUsedProducts(null,$_product);
foreach($childProducts as $child) { //cycle through simple products to find applicable
$simpleArray[$child->getVendor()][$child->getColor()] = $child->getPrice();
var_dump ($simpleArray);
}
Javascript:
var simpleArray = <?=json_encode($simpleArray)?>;
//..lots of unrelated code
for(var i=0; i < IDs.length; i++)
{
console.log(simpleArray);
//which color id is selected
var colorSelected = $j("#attribute92 option:selected").val();
console.log('Value of color selected is ' + colorSelected);
$j('.details'+data[i].vendor_id).append('<li class="priceBlock">$'+simpleArray[i][colorSelected]+'</li>');
}
Edit:
I have gotten rid of the simpleArrayJson declaration in the php and changed the first line of the javascript.
The is no reason for you to json_decode() the value you are trying to output. Just echo it directly:
var simpleArray = <?= $simpleArrayJson ?>;
This will output a javascript object literal.
Remove from the php.
$simpleArrayJson=json_encode($simpleArray, JSON_FORCE_OBJECT);
here you are converting the php array into a json string.
Change in the javascript
var simpleArray = <?= json_encode($simpleArray, JSON_FORCE_OBJECT); ?>;
Here you are just outputting the sting. previously you where doing this
var simpleArray = <?=(array) json_decode($simpleArrayJson)?>
which after json_decode was returning an array, which you where casting to an array which then was cast to a string by the <?= so what ended up going to your browser was something like:
var simpleArray = Array;
try a for in loop.
for( item in data ) {
console.log(data[item]);
}
this is because json has keys that match the indexes of the array that was json_encoded, instead of necessarily 0->n indexes.
Edit thanks to comments changed data.item to data[item]

json returning string instead of object

i have
$age = implode(',', $wage); // which is object return: [1,4],[7,11],[15,11]
$ww = json_encode($age);
and then i retrieve it here
var age = JSON.parse(<?php echo json_encode($ww); ?>);
so if i make
alert(typeof(<?php echo $age; ?>)) // object
alert(typeof(age)) //string
in my case JSON.parse retuned as string.
how can i let json return as object?
EDIT:
var age = JSON.parse(<?php echo $ww; ?>); // didnt work , its something syntax error
implode returns a string, so it is only natural that json_encode encodes it as such. It does not recognize already JSON-like data passed as a string.
If you want to get an object, you have to pass an associative array to json_encode:
$foo = array(
1 => 4,
7 => 11,
15 => 11
);
echo json_encode($foo); // {1:4,7:11,15:11}
With so little info about what $wage looks like before it's imploded, it's hard to tell exactly what you want to get. How is that structure ([1,4],[7,11],[15,11]) an object? Is the first element of each tuple a key? That's what I assumed with my example, but it might be off.
var age = [<?php echo $age; ?>];
a. You get a syntax error because you need to enclose the string within quotes, like so:
var age = JSON.parse("<?php echo $ww; ?>");
b. Moreover, you don't need JSON.parse. You can simply echo the php var after it was already json_encoded in the server side:
var age = <?php echo $ww; ?>;
JSON.parse is there to convert a JavaScript string to an object. In the case of PHP string, once it is built as JSON, echoing it in the right place is equivalent to coding it yourself.

how to make the json data into jquery code?

the php json_encode($object) result is
[{"price_id":"1","website_id":"0","price_qty":2,"price":"90.0000"},
{"price_id":"2","website_id":"0","price_qty":5,"price":"80.0000"},
{"price_id":"3","website_id":"0","price_qty":8,"price":"70.0000"}]
someone tell me, var sorted = arrayWithJsonData.sort(function(a,b){}
how to use the above php json_encode($object) to arrayWithJsonData.
i used the following way, but it shows TypeError: object.sort is not a function
first: in php i did: echo '<div style="display:none;" id="object">'.$object.'</div>'; then using in jquery
var object=jQuery("#object").text(); // first sort the array var sorted = object.sort(function(a,b){}
You need to parse the object first so javascript(jQuery) can understand it:
JSON.parse(data);
var arrayWithJsonData = $.parseJSON($('#object').text());
$.parseJSON is a jQuery utitlity for converting a well-formed json string to a json object (jQuery doc: http://api.jquery.com/jQuery.parseJSON/). In our case, $('#object').text() method of the matched element returns the well-formed json string which is the output of the PHP function json_encode($object). Hope that helps.
var arrayWithJsonData = <?php json_encode($object) ?>;
var sorted = arrayWithJsonData.sort(function(a, b){
// Sort criteria between a and b
});

foreach for javascript, json array

I have a JSON array that looks like this:
[{"RegDate":"31-03-2011"},{"RegDate":"29-07-2011"},{"RegDate":"09-08-2011"},{"RegDate":"09-08-2011"},{"RegDate":"09-08-2011"},{"RegDate":"12-08-2011"},{"RegDate":"15-08-2011"},{"RegDate":"15-08-2011"},{"RegDate":"23-08-2011"},{"RegDate":"07-09-2011"},{"RegDate":"09-09-2011"},{"RegDate":"13-10-2011"},{"RegDate":"13-10-2011"},{"RegDate":"13-10-2011"},{"RegDate":"25-10-2011"},{"RegDate":"25-10-2011"},{"RegDate":"03-11-2011"},{"RegDate":"03-11-2011"},{"RegDate":"11-11-2011"},{"RegDate":"16-11-2011"},{"RegDate":"18-11-2011"},{"RegDate":"21-11-2011"},{"RegDate":"02-12-2011"},{"RegDate":"02-12-2011"},{"RegDate":"12-12-2011"}]
The code to get this json array is as of the following:
var unavailableDates1 = jQuery.parseJSON('<?php echo json_encode($noticesDates) ?>');
I am trying too get all of the dates in that array (which was originally a multidimensional array), and put it inside one array:
var unavailableDates = ["9-3-2012", "14-3-2012", "15-3-2012"]; for example
I am unsure of how to do this, I have tried a foreach but wasn't successful.
All help will be appreciated.
First of all, that parseJSON is unnecessary and actually dangerous. Take it out:
var unavailableDates1 = <?php echo json_encode($noticesDates) ?>;
Then, just use jQuery.map:
var unavailableDates = $.map(unavailableDates1, function(item) {
return item.RegDate;
});
Using a string like that is dangerous for the following three objects, for example:
{"key":"Backslash here: \\"}
{"key":"I'm a horse!"}
{"key":"Some\\backslash"}
They become, respectively:
SyntaxError: Unexpected end of input (Single escape escapes end of string)
SyntaxError: Unexpected identifier (Unescaped single quote breaks out of the string, actually an XSS vulnerability)
Object
key: "Someackslash" (\\b becomes the \b backspace control character)
__proto__: Object
You could escape it again, but there's no need; valid JSON is always a valid JavaScript object, and you can trust your own PHP not to include injection code in there.
var justDates = [];
for (var i=0; i < unavailableDates1.length; i++) {
justDates.push(unavailableDates1[i]['RegDate']);
}
Each Object ({'RegDate:'date'}) is an item in a javascript array. To get an item you use a numerical index. so to get the first item would be theArray[0] this would give you {"RegDate":"31-03-2011"}. Then to get that particular date string you just have to use the key theArray[0]['RegDate']!. So since you want to go through every member of a list, you should get the list length using .length.
For loops are usually used for this type of iteration and not for..in. because for in can access properties that are undesired! http://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/
have a look at how to iterate over an array.
You can do something like:
dates = new Array();
unavailableDates1.forEach(function (obj){
dates.push(obj.RegDate);
};
Try the following:
JavaScript:
var x = [{"RegDate":"31-03-2011"},{"RegDate":"29-07-2011"},{"RegDate":"09-08-2011"},{"RegDate":"09-08-2011"},{"RegDate":"09-08-2011"},{"RegDate":"12-08-2011"},{"RegDate":"15-08-2011"},{"RegDate":"15-08-2011"},{"RegDate":"23-08-2011"},{"RegDate":"07-09-2011"},{"RegDate":"09-09-2011"},{"RegDate":"13-10-2011"},{"RegDate":"13-10-2011"},{"RegDate":"13-10-2011"},{"RegDate":"25-10-2011"},{"RegDate":"25-10-2011"},{"RegDate":"03-11-2011"},{"RegDate":"03-11-2011"},{"RegDate":"11-11-2011"},{"RegDate":"16-11-2011"},{"RegDate":"18-11-2011"},{"RegDate":"21-11-2011"},{"RegDate":"02-12-2011"},{"RegDate":"02-12-2011"},{"RegDate":"12-12-2011"}];
var ary = new Array();
for (foo in x) {
ary.push(x[foo].RegDate);
}
console.log(ary);
jsFiddle example.
I noticed you tag jquery in here as well so, here's a jquery solution:
http://jsfiddle.net/aztechy/DK9KM/
var foo = [
{"RegDate":"31-03-2011"},
{"RegDate":"29-07-2011"},
{"RegDate":"09-08-2011"},
{"RegDate":"09-08-2011"}
];
var datesArray = [];
$.each(foo, function() {
datesArray.push(this.RegDate);
});
console.log(datesArray);​
Try This, it may works.
var unavailableDates = [];
for(var i = 0; i < unavailableDates1.length; i++){
unavailableDates[i] = unavailableDates1[i].RegDate;
}
for(var i=0;i<unavailableDates.length;i++) {
unavailableDates[i] = unavailableDates[i].RegDate;
}

Categories