how can I correct php/json syntax error? - php

I can retun this with json/php
exit('[{"name":"signup","state":"1","message":"this is a message"}]');
but not this:
$_SESSION["message"] = 'link: here ';
exit('[{"name":"signup","state":"1","message":"'.$_SESSION['message'].'"}]');
how can correct it?

JSON uses double quotes to encapsulate strings, and you're simply concatenating in a string that contains unescaped double quotes which breaks the encoding.
To ensure that all of your data is encapsulated and encoded properly do something like:
$data = [
'name' => 'signup',
'state' => '1',
'message' => $_SESSION['message']
];
echo json_encode($data);
exit();
json_encode() handles escaping, encoding, conversions, and anything else necessary to produce properly-formatted JSON.

If you want this at easiest way , follow my steps.
Dont make JSON manually..
Use this:
Make an array first.
Than use json_encode . You will get your data. correctly.

Related

Correct way of adding text + php variable in json string?

I am struggling a bit to find the correct way of adding a php variable in my json string, with text added just in front of the variable. This is what I have got so far...
$postData = '
{
"message": "Web order '.$order_number.'"
}
';
When I look at the printout there is a line break just after "Web order", but otherwise nothing seems to go wrong... is this the way to do it?
If you want to use json string, then make sure you have properly use your values in your array.
Example:
<?
$order_number = 1;
$yourArray = array('message'=>"Web order ".$order_number);
echo json_encode($yourArray);
?>
Result:
{"message":"Web order 1"}
Here, i am using an array for your data $yourArray and then use json_encode() for json string.
DEMO
Instead of concatenate string, use sprintf()
Dealing directly with Json can become very harmful quickly. Prefer to use array then json_encode instead.
in your case, here is a simple example:
$message = sprintf('Web order %s', $order_number)
$postData = [
'message' => $message
];
$json = json_encode($postData);

How to remove quotes from numerical array value

How can I let my PHP server respond with some thing like this:
{"eCode":0,"city":"london","time":"15:35"}
not:
{"eCode":"0","city":"london","time":"15:35"}
I'm using this PHP code:
<?php
$data = array('eCode' => '0', 'city' => 'london', 'time' => '15:35');
header('Content-type: application/json');
echo json_encode($data);
?>
So how can I remove the quotes from "eCode":"0", and replace it with "eCode":0, ?
You're quoting the zero, making it a string. Just leave it as a int:
<?php
$data = array('eCode' => 0, 'city' => 'london', 'time' => '15:35');
echo json_encode($data);
?>
This answer reiterates some things that were already said by others, but hopefully a little more explanation will be helpful.
Basically, the zero is quoted in the output of json_encode($data) because it is quoted in the input.
json_encode will not automatically convert numeric strings to integers, unless you have set the JSON_NUMERIC_CHECK option, for example:
echo json_encode($data, JSON_NUMERIC_CHECK);
If you are constructing the array you're attempting to json_encode with your code, then you should be able to simply add ints rather than numeric strings into the array as you build it:
$data['eCode'] = 0; // use 0 instead of '0'
$data['city'] = 'london';
$data['time'] = '15:35';
However, if the array you're working with is coming from some other source, such as a query result, you'll need to decide between several options:
Use JSON_NUMERIC_CHECK when you json_encode (keep in mind that it won't only convert that column to a number; it will convert anything that looks like a number - you can see various warnings about that in the comments on this answer and on the PHP documentation)
Figure out how to make adjustments to the data source or the way you fetch the data so that the array you get will already have ints instead of strings (for example, turning off emulated prepares in PDO)
Convert the value in the array before you json_encode. There are various ways to do that, $data['eCode'] = (int) $data['eCode'];, for example.
In my opinion, option 2 would be the best way to handle it.

Prevent strtotime being encoded as string by json_encode

I am building data for a status dashboard that uses Highcharts.js, and loading it with ajax, however when using json_encode my timestamps are getting quoted, which means Highcharts chokes on them.
The code is:
$responseData = array();
foreach ($monitors as $monitor => $data) {
foreach (array_reverse($data['responsetime']) as $responsetime) :
$responses[] = array(strtotime($responsetime['datetime'])*1000 => $responsetime["value"]);
endforeach;
$responseData[] = array('name' => $data['friendlyname'], 'data' => $responses);
}
$responseData = json_encode($responseData,JSON_NUMERIC_CHECK);
Using JSON_NUMERIC_CHECK prevents problems with the value, but the key (a timestamp) gets quoted still.
Example output:
[{"name":"Series 1","data":[{"1432933860":1622},{"1432935660":1458},{"1432937461":1388}]},{"name":"Series 2","data":[{"1432933860":1622},{"1432935660":1458},{"1432937461":1388}]}]
Desired output:
[{"name":"Series 1","data":[{1432933860:1622},{1432935660:1458},{1432937461:1388}]},{"name":"Series 2","data":[{1432933860:1622},{1432935660:1458},{1432937461:1388}]}]
What am I doing wrong? Are keys always quoted perhaps?? Any way around this?
http://json.org/
From Objects
An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string.
and from Strings
A string begins and ends with quotation marks.
So I would say that according to the standard: yes, you should always quote the key. Maby you could try to escape that key in javascript? Store them in a value and remove all non-numeric characters?
Something like:
myJsonKey = myJsonKey.replace(/\D/g,'');

What kind of php array is this and how do I edit it?

I am working with a project that is coded in php OOP. I have created a form that post back to itself and gets those values and puts them into a predefined array format. I say predefined because this is the way the previous coder has done it:
$plane->add(array('{"name":"Chris","age":"22"}','{"name":"Joyce","age":"45"}'));
So when I get my values from the $_POST array, I thought it would be simple, so I tried
$plane->add(array("{'name':$customerName,'age':$customerAge}"));
This is triggering an error though, it seems it's passing the actual name of the variable in as a string instead of it's value. So how do I pass those values in to that function. While we are on it, can someone explain what kind of array that is, I thought arrays were always $key=>value set, not $key:$value.
As other comments and answers have pointed out, the data is being serialized in a format known as JSON. I suggest reading up on json_encode() and json_decode()
To make your example work, you would have to do:
$data = array("name" => $customerName, "age" => $customerAge);
$plane->add(array(json_encode($data));
That looks like json:
http://sandbox.onlinephpfunctions.com/code/e1f358d408a53a8133d3d2e5876ef46876dff8c6
Code:
$array = json_decode('{"name":"Chris","age":"22"}');
print_r( $array );
And you can convert an array to json with:
$array = array("Customer" => "John");
$arrayJson = json_encode( $array);
So to put it in your context:
$array = array("Name"=>"Chris", "age" => 22);
$array2 = array("Name"=>"John", "age" => 26);
$plane->add(array( json_encode( $array),json_encode( $array2) );
It looks like it could be JSON, but might not be.
Be careful to quote everything like they have done, you didn't have any quotes around the name or age.
I've added the same sort of quotes, and used the backslashes so that PHP doesn't use them to end the string:
$plane->add(array("{\"name\":\"$customerName\",\"age\":\"$customerAge\"}"));
Be wary of user data, if $customerName and $customerAge come from POST data, you need to properly escape them using a well tested escaping function, not something you just hack together ;)
It looks like your array is an array of JSON encoded arrays. Try using:
$plane->add(array('{"name":"' . $nameVar . '","age":"' . $ageVar . '"}', ...));
If you use the following:
echo json_encode(array('name' => 'Me', 'age' => '75'), array('name' => 'You', 'age' => '30'));
You will get the following string:
[{"name":"Me","age":"75"},{"name":"You","age":"30"}]
I believe you are getting an error because what you are trying to pass to the function is not JSON while (It looks like ) the function expects an array json strings, Manually trying to write the string might not be a good idea as certain characters and type encode differently. Best to use json_encode to get you json string.
$plane->add(array(json_encode(array('name'=>$customerName,'age'=>$customerAge))));

Unable to eval a string array

How can i change this to a JSON Array? im using the eval technique but this is not working. Im getting this kind of response from our upx server:
array(
'invoice' => array(
'id' => '4',
'realid' => '4',
'address_rev' => NULL,
'relation_data_id' => '3',
'contact_set_rev' => '3',
'business_data_rev' => '4',
'private_data_rev' => NULL,
// etc..
)
);
var_dump($newdata); // String
eval("\$newdata = \"$newdata\";");
var_dump($newdata); // Still stays as a string as shown above....
Any clue?
Ty Already!
You'll facepalm really bad when I tell you this..
But the reason it's still a string is because you wrapped it in "" inside your call to eval, and of course wrapping letters inside of quotes will make it.. (drum roll ..) a string.
eval ('$newdata = ' . $newdata . ';'); // this will do what you want
If you want to turn it into json right away, use the below:
eval ('$newdata = json_encode (' . $newdata . ');');
PHP: json_encode - Manual
var_dump($newdata); // String
eval("\$newdata = $newdata;");
var_dump($newdata); // Still stays as a string as shown above....
// eval("\$newdata = \"$newdata\";");
// ^ ^
Remove the double quotes. Your just putting it back into a string...
Although as I said above, if you want to transmit a PHP array, you should be using serialize()
You can try json_encode of php. you can try
$json_array = json_encode($your_array);
This will give you json encoded array. Then you can do json_decode on $json_array to get original contents back
Check if your php has JSON extension

Categories