How to generate a javascript like object in php - javascript

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;

Related

Pushing a PHP array values into the JavaScript array?

I am working with Blockly to make some Blocks. All the errors came up when I am making Blockly Blocks.
IS there anyone who knows why my code is not working in Blockly?
I have a URL including a set of JSON code.
I got the content in a myPhp.php file using:
$data = file_get_contents("URL");
and then, I decode the data using:
$objects = json_decode($data, true);
$objects contains:
[0] => Array
(
[name] => Light
[x] => 5
[h] => 5
[y] => 5
[status] => on
)
Now I want to push this array of data into a JavaScript array using:
<script type="text/javascript">
var obj = new Array();
<?php
foreach($objects as $key => $value){
?>
obj.push('<?php echo $value; ?>');
<?php } ?>
</script>
And $value needs to have all those data.
But I am getting Invalid or unexpected token JavaScript error. and when I look at to the source code, it shows the error is related to this line: obj.push and it says obj.push('<br /> <b>Notice</b>: Array to string conversion in <b>myPhp.php</b> on line <b>20</b><br /> Array');.
Your $value itself is an array and here your $key is 0.
$key
[0] =>
$value
Array
(
[name] => Light
[x] => 5
[h] => 5
[y] => 5
[status] => on
)
So you need another loop for $value to obtain each value like thus
<script type="text/javascript">
var obj = new Array();
<?php
foreach($objects as $key => $value){
foreach($value as $key1 => $value1){
?>
obj.push('<?php echo $value1; ?>');
<?php } }?>
</script>
Instead of going through the hassle of looping through the array or even decoding it (unless there is a specific reason to do so), just use json_encode. JSON is JavaScript's native language, so it will understand it.
<?php
$data = json_decode(file_get_contents("URL"));
?><script type="text/javascript"><?php
// echo out JSON encoded $data or a string of '[]' (empty JS array) if it is a false value (error occured with json_decode)
?>var obj = <?= json_encode($data) | '[]' ?>;<?php
// In JavaScript "Light" is available as obj[0].name or it does not exist (empty array if an error occured with json_encode or json_decode)
?></script>
A few things to get you started:
JSON is "JavaScript Object Notation". Though it is used in many other languages, JavaScript understands it natively.
This means that once you've got a JSON string, you can get a JavaScript object out of that directly. If the JSON string represents a single object, you'll get a single JavaScript object. If it represents an array, you'll get a JavaScript array of JavaScript objects. If it is some nested structure, then you'll get just that. In a modern browser all you need on the JavaScript side is
JSON.parse(...) to do the magic.
To get the JSON into JavaScript, either:
Get it in JavaScript directly, using XMLHttpRequest or helpers such as jQuery's $.get. That will need you to understand some asynchronous programming, so maybe indeed one of the following is easier to start with:
Get it in PHP, parse it like you tried in your question, and then generate proper JavaScript to create a JavaScript object or array again. Note that PHP's json_decode gets you some associative array, which you then need to map to a JavaScript object.
Get it in PHP, do not parse it at all, and simply forward the JSON string to JavaScript and parse it there, using JSON.parse.
Get it in PHP, use Jim's simple solution to get it into JavaScript.
When generating JavaScript in PHP, you need to be careful with quotes, newlines and other special characters in string values. Like if the JSON is:
{"quote": "She said: 'Beware', and walked off"}
...then you cannot just concatenate text into obj.push('...') as that would create invalid JavaScript:
obj.push('She said: 'Beware', and walked off');
Above, JavaScript does not know what to do with the text after the second single quote, and throws Uncaught SyntaxError: missing ) after argument list. Likewise, newlines may be troublesome, like when unexpectedly getting a PHP error while generating the JavaScript (for reasons explained in Osama's answer), which will yield invalid JavaScript and throw Invalid or unexpected token:
obj.push('<br />
<b>Notice</b>: Array to string conversion
in <b>myPhp.php</b> on line <b>20</b><br /> Array');
In the JSON example above, you could use double quotes in obj.push("..."), to generate:
obj.push("She said: 'Beware', and walked off");
But in general you might not know what values you get, so you need to "escape" troublesome characters.
I don't know enough about PHP to know what's the best way to escape the strings. As (valid) JSON uses double quotes, it should already have escaped double quotes when needed. So, a JSON string might look like:
{"quote": "She said: \"Beware\", and walked off.\n\nWe'll remember her."}
Above, you need to take care of the backslashes that JSON already added for escaping. So PHP's addslashes might do, bus I did not test this:
<script type="text/javascript">
var obj = JSON.parse("<?= addslashes($data) ?>");
</script>
Otherwise, when first parsing $data into a PHP object using json_decode (or when not even doing that!), Jim's simple solution is certainly preferred.

Creating "objects" and "arrays" in PHP in a way that would allows JS to distinguish between them

PHP's syntax to create an array (either indexed or assosiative) is the same, aka
$arr = [];
However, json_encode will convert an empty PHP "array" (note the quotes) to an empty JS array ([]), which is not desirable in certain situations.
Is there a way I can create an empty assosiative array in PHP, so json_encode will convert it to an empty JS object, aka {}, instead of [].
You can use stdClass:
$obj = new stdClass();
echo json_encode($obj);
This gets me the intended {} output.
Use a stdClass():
php > $x = new StdClass;
php > echo json_encode($x);
{}
Of course, once it's a stdclass, you wouldn't be able to use it as an array anymore. But this is at least one way of forcing an empty object in JSON, so you could just special-case your code:
if (count($array) == 0) {
$json = json_encode(new StdClass);
} else {
$json = json_encode($array);
}
You can just pass the JSON_FORCE_OBJECT option to the json_encode function. This will force any empty arrays to be objects as well.
JSON_FORCE_OBJECT (integer) Outputs an object rather than an array
when a non-associative array is used. Especially useful when the
recipient of the output is expecting an object and the array is empty.
Available since PHP 5.3.0.
So:
if (empty($array)) {
$json = json_encode([], JSON_FORCE_OBJECT);
} else {
$json = json_encode($array);
}
This looks cleaner than converting an object in my opinion.
Or even
$json = json_encode($array, empty($array) ? JSON_FORCE_OBJECT : 0);

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

PHP shows "{" or "[" for JSON Object Attributes sent via Angular $http

I've never seen this problem before, and I can't find the issue anywhere online. I'm using Angular to post form data to a PHP page. I'm using the file_get_contents() method of retrieving the POST data, which is a simple JSON object.
The problem arises with the data attributes - when I assign php vars to the data, they always have the value "{" or "[" (I echo'd and logged them). Any idea what could be causing this problem?
The relevant form declaration:
<form name="itemForm" ng-if="true" id="newItemForm" class="add-item" ng-submit="addItem(itemForm)">
<input type="text" class="form-control data-entry" ng-model="itemForm.itemType" placeholder="Type" ng-focus="true">
Here's my Angular function:
$scope.addItem = function(itemForm) {
$http.post("../ajax/addItem.php", itemForm).success(function(data) {
//console.data(JSON.stringify(itemForm));
console.log(data);
currItem = itemForm;
itemsArr.push(angular.copy(itemForm));
$scope.itemForm = defaultForm;
getItem();
});
};
partial PHP:
<?php
$params = file_get_contents('php://input');
if($params){
$item = $params["item"];
$type = $item["itemType"];
//get other parameters, insert into MySQL database
echo json_encode(["type = " => $type]);
}
?>
You're using string-based keys for your array. In Javascript terms, that has to be represented as an Object, which uses {} as the delimiters. Proper arrays, which use [], only accept numerical keys.
And note that type = as an array key is somewhat redundant. Why not just type?
The file_get_contents function returns a string, so the $params variable is a string not an array. However, strings in php can be accessed in an array like fashion (except the key must be a number). In your code $item = $params["item"] should will give you a php warning and php will automatically assume an index of 0 since the key you gave was not a number. This is why you were getting { or [ when you echoed the data from php (because valid json is enclosed by {} or []).
To use $params as an array like you are trying to do you first need to do $params = json_decode($params). This will only work assuming you have a valid json string in the file you are reading from.

JS variable inside JSON string from PHP

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.

Categories

Resources