Being hitting my had for a few days and finally came to realize that my json syntax is not being accept by php json_decode. It seems to work only when the value is a integer, not a string. How can I manage to use a json such as the following to work?
<?php
$json = '{"fname":2,"surname":2}'; //return No errors
// $json = '{"fname": SJ011MS,"surn": something}'; //return Syntax error, malformed JSON
$obj = json_decode($json, true);
switch (json_last_error()) {
case JSON_ERROR_NONE:
echo ' - No errors';
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
echo ' - Unknown error';
break;
}
?>
essentially I'm planning to use a json such as:
{"widget": {
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}}
This is definitely malformed JSON:
$json = '{"fname": SJ011MS,"surn": something}'
You have to enclose the strings using "
(not even single quotes '
). It should really be:
$json = '{"fname": "SJ011MS","surn": "something"}'
//-----------------^-------^---------^---------^
JSON can have only the primitive JavaScript types, arrays and objects.
This isn't valid JSON:
{"fname": SJ011MS,"surn": something}
The property values need to be in quotes as well:
{"fname": "SJ011MS","surn": "something"}
Considering your example json
{"widget": {
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}}
I have written following code, which seems to work perfectly:-
<?php
$json = '{"widget": {
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}}';
$decodedJson = json_decode($json,TRUE);
echo $json;
print_r($decodedJson);
?>
OUTPUT:
{"widget": {
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}}Array
(
[widget] => Array
(
[text] => Array
(
[data] => Click Here
[size] => 36
[style] => bold
[name] => text1
[hOffset] => 250
[vOffset] => 100
[alignment] => center
[onMouseUp] => sun1.opacity = (sun1.opacity / 100) * 90;
)
)
)
The Thing to Learn here is that if JSON property contains any string then it should be within "quotes".