How do I convert numeric values to strings? - php

I have a JS function which I'm passing some JSON. I produce this JSON with PHP:
<?php
$array[] = array('hello','123','456');
echo json_encode($array);
?>
This gives me something neat for JS like:
[["hello","123","456"]]
My JS function seems to like this format.
The problem I have however is when I produce a similar array directly in JS like so:
var json = [[text_var,number_var,number_var]]; // these vars established earlier in the code
var json_stringify = JSON.stringify(json);
I wind up with something that looks like this:
[["hello",123,456]]
So basically, it isn't encapsulating my numbers with quotes. I wouldn't think it would matter, but without them I get a Uncaught RangeError: Maximum call stack size exceeded
I tried doing something like preparing the JSON myself with:
var json = '[["'+place_name+'","'+longitude+'","'+latitude+'"]]';
But passing that it doesn't like either - maybe it isn't feeling it as a JSON var, and I've tried parsing that through JSON.stringify but I end up with backslashes before every quote and it doesn't like that either.
What is my feeble mind not seeing here?
EDIT: My PHP array is in another array hence the result of [["hello',"123","456"]] and not single brackets [ ]

Convert numbers to strings:
var json = [[text_var,number_var.toString(),number_var.toString()]];

JSON supports numbers (without quotes) and strings (with quotes). To force it to use strings, try:
var json = [[text_var,number_var + "",number_var + ""]];

Related

Best way to json encode an array that has a json encoded value already? PHP

I have an array with multiple items in it one of which is an already encoded json string. I'm wanting to json encode the whole array but in doing so it re-json_encodes the json and adds slashes to it. The only way I've found to fix this is to json_decode the value and then encode the whole array. I feel like this is a waste of resources though and I feel like there has to be a better way. Is doing it that way the best possible way?
Here's a sample of the array I'm trying to json_encode.
$arr = array();
$arr["var1"] = '{"test":"test"}';
$arr["var2"] = 'foo';
$arr["var3"] = 'bar';
If I don't decode the var1 first and I just encode the whole array I get a result like so
{"var1":"{\"test\":\"test\"}","var2":"foo","var3":"bar"}
Notice the slashes in the json object.
json_encode() returns a string containing the json representation of a value.
In the example, a php string is passed as one element of the array '{"test":"test"}', thus json_encode() is encoding it appropriately into json format, with escaped quotes "{\"test\":\"test\"}".
If decoding nested json is a very resource heavy task, a workaround is to use a placeholder instead of the value, {"var1":"PLACEHOLDER","var2":"foo","var3":"bar"}, and then using str_replace() to replace it.
However, simply decoding it as you described is probably a cleaner solution, if its not resource heavy.

json_encode Returning a PHP Array

So I am working with PHP to pass a PHP array over a jQuery Ajax request to another PHP page. This is quite the task. For some reason, my json_encode is returning an array instead of a string, I am not quite sure why. Here is my PHP code:
$new_spreadsheet = nl2br($_POST['spreadsheet']);
$new_spreadsheet = explode('<br />', $new_spreadsheet);
array_shift($new_spreadsheet);
$new_spreadsheet = array_values($new_spreadsheet);
echo json_encode($new_spreadsheet);
I would show you the output, but it is really long. Basically this is outputting a PHP array which consists of each row on the spreadsheet. This is what I want to have, but the problem is that I don't want the quotes and everything in the array. I am pretty sure I need to run json_decode, but when I do that my code returns an error saying that the parameter needs to be a string. I can tell something is not right, but am not quite sure what I need to change. I would appreciate any advice.
Update: At this point, when I try to loop through the array and print each value, the first array index is equal to a double quote like so: ". There are double quotes in random values throughout the area. I am not quite sure about what is causing this.
If I echo the rows from within the json_encoded PHP array onto the console, I get the following output:
"
correct value
correct value
correct value
"
You're using JSON, which means you have to adhere to somewhat more stringent syntax rules than Javascript's. e.g.
<?php
$arr = array('This' => 'is', 'an' => 'array in php');
echo json_encode($array);
?>
output:
{"This":"is","an":"array in PHP"}
There is NO way to avoid getting quotes on the values, as they're a fundamental requirement of JSON (and Javascript). If you don't want quotes, then don't use JSON.
try only br.
$new_spreadsheet = explode("<br>", $new_spreadsheet);
It will work. and json_enode can never return an array. try var_dump and check.Also make sure before you post, use htmlspecialcharacters.

Pass PHP Array to Javascript

Am trying to pass an array of values from PHP function to Javascript. Not sure if I am doing it correctly.
PHP:
function toggleLayers(){
for($i=0;$i<$group_layer_row;$i++){
$toggleArray=mb_convert_encoding(mssql_result ($rs_group_layer, $i, 0),"UTF-8","SJIS")."_".mb_convert_encoding(mssql_result ($rs_group_layer, $i, 1),"UTF-8","SJIS");
return $toggleArray;
}
}
JS:
var myArray = [JSON.parse("<?php echo json_encode($toggleArray); ?>")];
for(var i=0;i < myArray.length; i++){
if($myArray.getVisibility()==true){
$myArray.getVisibility(false);
}
else{
$myArray.getVisibility(true);
}
}
SQL (for reference):
$con = mssql_connect("myServer", "myUsername", myPassword");
$sql = "SELECT * FROM m_group_layer WHERE group_id=\"".$_SESSION["group_id"]."\" ORDER BY display_order";
$rs_group_layer = mssql_query ($sql, $con);
$group_layer_row = mssql_num_rows($rs_group_layer);
I have been looking at some other similar questions, and the answers are either vague and/or there are a few thousand of them.
Would appreciate any help, also please try to explain as if you were writing a book called "Idiot's Guide to Passing PHP Arrays to JS"
Thanks for your help.
Edit:
Sorry, my question was very vague. Here's what I'm trying to do:
1.PHP Function gets all records from table into array(in this case they are map layers)
2.Javascript receives PHP array and loops through adding if clause to toggle layers.
Hope this makes it clearer.
It's simpler than you think.
Change this line:
var myArray = [JSON.parse("<?php echo json_encode($toggleArray); ?>")];
To just:
var myArray = <?php echo htmlspecialchars(json_encode($toggleArray), ENT_NOQUOTES); ?>;
json_encode produces a json string. Echoing the string into a javascript context is the equivalent of a javascript literal. The htmlspecialchars is just for the necessary html escaping and is not unique to echoing json.
NOTE however that you can only json_encode a php object or array, not any scalar types like ints or strings. This is a limitation of JSON itself. In your toggleLayers() function, you are returning a string, not an array.
A thing that would be very useful to understand:
You sumply can't "pass an array of values from PHP function to Javascript".
But rather you have to create the javascript code using PHP just like you are creating HTML.
Thus, 3 simple step to solve any problem with PHP -> client transfers:
Create a pure client-side code you wish. Make it work. Save it somewhere.
Create a PHP code to produce that client-side code.
Compare the codes. If doesn't match - correct the PHP code. Repeat until done.

convert JSON object to query string and then back to an object

I know this has been asked a few times but please bear with me.
I have a google maps object which is rather complex (it contains various nodes, coordinates, etc) and I am trying to pass it as a query string.
I need a play javascript/jQuery solution.
I have tried the .param method which gives a jQuery error. The only thing that works is the "stringify" method which then creates a string that when appearing as a url looks a bit like this: %7B%5C"shape_1%5C"%3A%7B%5C"color%5C"%3A%5C"%237F0000%5C"%2C%5C"data%5C"%3A%7B%5C"b%5C"%3A%5B%7B%5C"Na%5C"%3A51.56727431757122%2C%5C"Oa%5C"%3A-0.10462402858888709%7D%2C....
php translates that as:
{\\"shape_1\\":{\\"color\\":\\"#7F0000\\",\\"data\\":{\\"b\\":[{\\"Na\\":51.56727431757122,\\"Oa\\":-0.10462402858888709},...
but having said that I don't want to use PHP, I am just showing you what it does in case it helps you see what stringify did to the object.
After I unescape with Javascript it looks a bit more normal like:
{\"shape_1\":{\"color\":\"#7F0000\",\"data\":{\"b\":[{\"Na\":51.56727431757122,\"Oa\":-0.10462402858888709},..
So as you can see, the unescaped sequence has these slashes everywhere.
When I try to evaluate that into a JSON object I get "Illegal token \". The parse method also fails. I just can't find any way to put this string back into the complex JSON object that it was.
I have looked online for various suggestions but they fail. I also don't understand why stringify injects all these slashes which simply shouldn't be there.
If anyone has an idea how to take that object, put it in a query string and then parse it back I would be very grateful.
Nick
Update:
The answer is this:
encodeURIComponent(JSON.stringify(myObject));
And then on the receiving end:
var a = querySt("data");
var b = decodeURIComponent(a);
var c = unescape(b);
var d = JSON.parse(c);
or all in one line
JSON.parse(unescape(decodeURIComponent(querySt("data"))));
Nick
See http://php.net/manual/de/security.magicquotes.php - you have to turn off magic quotes. They are old, deprecated stuff, they are insecure and break stuff.
Magic Quotes is a process that automagically escapes incoming data to the PHP script. It's preferred to code with magic quotes off and to instead escape the data at runtime, as needed.
Howto: http://www.php.net/manual/de/security.magicquotes.disabling.php
Try this to convert query string into json object
var queryStringToJSON = function (url) {
if (url === '')
return '';
var pairs = (url || location.search).slice(1).split('&');
var result = {};
for (var idx in pairs) {
var pair = pairs[idx].split('=');
if (!!pair[0])
result[pair[0].toLowerCase()] = decodeURIComponent(pair[1] || '');
}
return result;
}
You can use jQuery.param method to covert json object back to query string

json_encode remove quotes from keys?

If I use json_encode() on an array like this:
return json_encode(array( 'foo' => 'bar'));
The return is:
{'foo' : 'bar'}
The key is passed as a literal, and that is tripping up my script. What I really need is:
{ foo : 'bar' }
Does json_encode do that or do I have to strip the quotes out myself with some ugly regex?
When I test this portion of code :
echo json_encode(array( 'foo' => 'bar'));
die;
I get :
{"foo":"bar"}
Which is valid JSON.
(Note these are double-quotes, and not simple-quotes as you posted)
The ouput you are asking for :
{ foo : 'bar' }
is valid Javascript, but is not valid JSON -- so json_encode will not return that.
See json.org for the specification of the JSON format -- which is a subset of Javascript, and not Javascript itself.
Instead of "stripping the quotes out myself with some ugly regex", you should adapt your code, so it accepts valid JSON : this is way better, in my opinion.
No, json_encode will not do this for you. The json specification specifcally requires that keys be quoted strings. This is done to ensure that keys which are javascript reserved words won't break the data object.
If you want to convert your JSON to print a javascript object (that was my case) you can use ugly regex like this:
$myJsonString = preg_replace('/"([^"]+)"\s*:\s*/', '$1:', $myJsonString);
Source: https://hdtuto.com/article/php-how-to-remove-double-quotes-from-json-array-keys
How is it tripping up your script?
And per the JSON specification, key names are supposed to be strings. The 2nd snippet you posted is not valid JSON.
Thanks, everyone. I did not know that about the JSON spec. The issue was in fact with my script because I had not set the datatype of my $.ajax() function to "json"
What I learned today -- JSON and Javascript are not the same thing!

Categories