JSON.parse giving me object instead of result - javascript

I have variable in javascript which is coming from php by json_encode.
While I am psrsing it with JSON.parse(variable). It alert me objects instead of actual result.
CODE:
var a = '<?php echo json_encode($over_branch_array); ?>';
a = JSON.parse(a);
alert(a);
EDIT:
basically I need to map my php array.
a = a.map(function(v){
return { id : v.branch, text : v.branch };
});
If I will do JSON.stringify then I won't be able to do that..

alert performs a toString conversion on objects before displaying them. You'll get a result like this.
If you want to view the contents of the object, either console.log it or JSON.stringify it.
EDIT:
When I say use JSON.stringify I mean do it to show what is actually in the object:
alert(JSON.stringify(a));

Related

How to generate a javascript like object in php

I am trying to write empty object in my database: {} however, php is always adding quotation marks.
$model->maps = json_encode("{}");
so my output becomes "\"{}\""
And I can't use this either as it will output syntax error `$model->maps = json_encode({});
Also ['' => ''] is saving it as array instead of object. Or using empty array like = [], it saves it as []
What is the proper way of handling this case? All I want is empty javascript alike object = {}
Try this: https://3v4l.org/Vb0Mb
a string '{}' is already a valid json imo but if you want to use json_encode try the code below.
<?php
// Proper way
$jsonA = json_encode(new stdClass);
// This works but more complex
$jsonB = json_encode((object)array());
echo $jsonA;
echo PHP_EOL;
echo $jsonB;

while passing php 2d array to Javascript and try to parse using json_encode() It throws uncaught type error

I i try try to access passed php 2d array using json_encode function in javascript it throws the error that its an uncaught typeerror and the array is null, but if i print the contents of array in php only it is printing and having values in it. but it is not passing to javascript.
Both javascript and php are in same file.Below is simply a sample code snippet
var javascript_var = echo json_encode($Php_2D_array);
alert(javascript_var[0].OrderDate[1]); //javascript_var['OrderDate'].[1] earlier i tried to access like this because im having php variable index as a name as mentioned
Please help me sort out this problem
Thanks.
Try this:
var javascript_var = JSON.parse("<?php echo json_encode($Php_2D_array); ?>");
alert(javascript_var[0].OrderDate[1]);
First you need to convert to json and then javascript will take it as string, then you parse it in js.
you can encode array value in javascript by using instruction
JSON.stringify
if your array variable is in php then
var javascript_var = JSON.stringify('<?php echo $Php_2D_array?>');
if your array variable is in javascript
var javascript_var = JSON.stringify(var_array);

Create array from json_encode script without double quotes

*This question was created as I had no control over the JSON output at the time. So had to use JavaScript. If you have control over the JSON, refer to Mike Brant's answer. But Oka's answer solved my issue below and is a great solution..
I'm trying to create an array that doesn't contain double quotes from JSON.
I'm getting JSON and trying to build a system where I can push non quoted items to the array.
As I have no control over the JSON, I'm making it into a string and removing the double quotes and splitting it into an array again.
The problem is this still outputs the double quotes?
var artistJSON = '<?php echo $favourites ? json_encode($favourites->artists) : '[]' ?>';
var artistIds = artistJSON.replace(/"/g, '');
var artistAry = artistIds.split(',');
console.log(artistJSON);
console.log(artistIds);
console.log(artistAry);
Results from console;
["31","41","56","38","","27"]
[31,41,56,38,,27] //This is a string. I want an array.
["[31", "41", "56", "38", "", "27]"]
https://jsfiddle.net/1pu6nqu2/
Any help would be very grateful.
*Just to confirm, my aim of the game is to remove the double quotes from within the array.
Assuming you're trying to turn stringified JSON into an array, and turn the strings inside the array into numbers. You can use some combination of .map() and .filter() to achieve this.
http://jsbin.com/yojibeguna/1/edit?js,console
var artistJSON = JSON.parse('["31","41","56","38","","27"]')
.map(function (e) { return parseInt(e); })
.filter(function (e) { return isFinite(e); });
console.log(artistJSON, typeof artistJSON[0]);
If you are using json_encode() from PHP to dynamically populate the data structure, you should not populate into a string and then parse that string, just write directly to object/array literal. So change this:
var artistJSON = '<?php echo $favourites ? json_encode($favourites->artists) : '[]' ?>';
to this
var artist = <?php echo $favourites ? json_encode($favourites->artists) : '[]' ?>;
All I did was remove the single quotes (and change the variable name to something more appropriate). Now you have a data structure you can work with directly in javascript without need for additional parsing.
If the json data is stored as JSON data already, you do not need to re-encode it with php. Just echo it out and it will be assigned to your variable artistJSON.
Example:
var artistJSON = <?php echo $favourites ? ($favourites->artists) : '[]' ?>;
Edit: As Mike Brant said, you do need to re-encode it if it's not already stored as JSON literal data (in a db, or whatnot). I'm assuming it is.
Try this:
var artistJSON = '<?php echo $favourites ? json_encode($favourites->artists) : '[]' ?>';
var artists = JSON.parse( artisanJSON );
console.log( artists );
REF: How to json_encode php array but the keys without quotes
You can just run JSON.parse to convert the string to an array.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

jQuery/javascript: use PHP return value as javaScript array

is there anyway to import a javaScript array from a PHP return value?
Say that a PHP script, 'makeArray.php', would return '"first","second","third"' (without single quotes). The purpose of the below would thus be to alert 'second'.
$.get(makeArray.php, function(data){
var responseArray = new Array(data);
alert(responseArray[1]);
...
However all I get is 'undefined'. If I was to change the array index to [0], I would get '"first","second","third"'.
Thanks!
You can use JSON.
In PHP
$myarray = array('first','second','third');
return json_encode($myarray);
In JavaScript:
$.get(makeArray.php, function(data){
console.log(data[1]); //=> "second"
}, 'json');
Edit
If you don't have PHP 5.2 then you can try echoing a string and parsing it in JavaScript:
PHP:
echo join('%',$myarray);
JS:
var array = data.split('%');
Because, what you are doing is that you are including all the data recieved form the file (makeArray.php) into the first element of an array. So, obviously it would be in the zero-index of the array.
What you should do in this case is use Array.split() function on the array like - data.split(",") to create an array from the data recieved.

how to parse an associative array through json in javascript

I have a 2-D php array which i am encoding through JSON. My 2d array in php is something like this:
$array['A'][12] = 8;
$array['A'][8] = 21;
$array['B'][17] = 19;
$array['B'][9] = 12;
when I do echo json_encode($array); and alert this as Ajax xmlhttp.responsetext i get this in my alert box : {"A":{"12":"8","8":"21"},"B":{"17":"19","9":"12"}}
which is absolutely fine. Now i need to parse it in javascript so i used the JSON.parse() function. The problem is when i access the A and B fields of the string. I get this in my alert boxes: Object object. How to parse this associative array? I am a beginner in AJAX and JSON so please help.
var array = JSON.parse(yourResponseData);
array.A // Object
array.A['12'] //8
You can't access the key '12' via the dot syntax becase no variable name can start with a number.
You can use console.log() rather than alert() to see the complete structure of that parsed json object.
You can easily retrieve the value by using . notation or [] brackets:
For example:
var returned = JSON.parse(tran.responseText);
console.log(returned['A']['8']); //which should give you '21' based on your case

Categories

Resources