*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
Related
I want to pass php array in javascript code . when i use like this:
var resData = "{{ json_encode($data['calendarItems']) }}";
or this :
var resData = "{{ $data['calendarItems'] }}";
in both the result is :
[{"title":"rfvd vc","expired_at":"2018-12-31 00:00:00"}] //formatting
and JSON.parse return error. I can not get the array
There's two issues here. The first is that you're quoting the json output and the second is that the result is escaped to html entities.
Remove the quotes and output the result in raw format:
var resData = {!! json_encode($data['calendarItems']) !!};
Omitting the quotes around the result will remove the need to use JSON.parse(), since the variable will contain proper json from the start.
Read more about unescaped data in blade in the manual
When you do {{ }} it converts string elements inside into html entities. so { will be converted to "
I will suggest to use this package, which has cleaner implementation of passing data as usable js variables in your blade file.
You can try this:
var mapData = JSON.parse('<?php echo json_encode($latLng) ?>');
where $latLng is a PHP array.
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;
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));
I am generating a JSON string from a PHP array to echo a JS object.
This is what I want to get in js:
var myVar = 123;
//php output:
var obj = {a:1, b:[1,2], c: myVar, d:Date.UTC(2014, 0, 07)}
This is what I have:
<?php
$array = array('a'=>1, 'b'=>array(1,2), 'c'=>???, 'd'=>???);
echo json_encode($array);
?>
The question is: What I put in PHP instead of question marks so that it won't be converted to string?
JSON doesn't support variables or special Date objects. You can only use scalar values (strings, numbers, booleans), arrays and objects (associative arrays).
A way to get what you want would be to return a .js file and have the browser execute that (by including it as a script) instead of transferring simple JSON data. Otherwise you could only define "special" strings that are handled by the receiving side. (For example, array ["var", "myVar"] could be parsed accordingly.)
You could actually do something like that:
<?php
$array = array('a'=>1, 'b'=>array(1,2),
'c'=>'##myVar##',
'd'=>'##Date.UTC(2014, 0, 07)##'
);
$json = json_encode($array);
echo preg_replace('/\"\#\#(.*?)\#\#\"/', '${1}', $json);
?>
But in js JSON.parse won't work, so:
eval("var x = " + json_from_php);
Not such a good idea, but if you need it, it'll work. Just remember not to use this with any "json" which are generated not by your server.
$cw = array(chr(0)=>455,chr(1)=>455,...,'E'=>521,...chr(134)=>353,chr(135)=>353,...chr(255)=>465);
I have this file that defines an array as seen above (I have just shown a bit of the array for conciseness). Is this array assigning integer values to all of the ascii characters? If so why and also, how do I convert it to JavaScript?
I don't find it appropriate to explain to you why your code is defining any variables of an array, but please see this post on how to convert a php array to javascript.
https://stackoverflow.com/a/5619038/367456
Or you may use
var js_array = [<?php echo '"'.implode('","', $php_array).'"' ?>];