whatifif at yahoo dot com said something about a bug:
"When I try to decode JSON string {"a":"<p>test</p>"} into array on server-side, it fails."
That is not a valid JSON string, AFAICT. The JSON docs seem to say that '"','/' and '\' must be quoted with a '\'
$ php -r 'echo json_encode("<p>test</p>");'
"<p>test<\/p>"
So it was your '/' character screwing it over.
You probably shouldn't blindly run stripslashes on your $input either! The only time you would is if magic_quotes_gpc is turned on and your string is coming from one of the GPC.
I inherited some PHP code which used Services_JSON. It stopped working when we upgraded PHP and started using this function. The problem was they ran html_entity_decode() over the input and was being turned into a character incompatible with UTF-8.
json_decode
(PHP 5 >= 5.2.0, PECL json >= 1.2.0)
json_decode — Dekodiert eine JSON-Zeichenkette
Beschreibung
Konvertiert eine JSON-kodierte Zeichenkette in eine PHP-Variable.
Parameter-Liste
Rückgabewerte
Gibt den Wert von json im passenden PHP-Typ zurück. Die Werte true, false und null werden (unabhängig von Groß-/Kleinschreibung) entsprechend als TRUE, FALSE und NULL zurückgegeben. NULL wird zurückgegeben, wenn der Parameter json nicht dekodiert werden kann oder wenn die dekodierten Daten tiefer verschachtelt sind, als es der Parameter für Verschachtelungstiefe erlaubt.
Beispiele
Beispiel #1 json_decode()-Beispiele
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
Das oben gezeigte Beispiel erzeugt folgende Ausgabe:
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
Beispiel #2 Ein weiteres Beispiel
<?php
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
?>
Beispiel #3 Häufige Fehler bei der Verwendung von json_decode()
<?php
// die folgenden Zeichenketten sind gültiges JavaScript aber kein gültiges JSON
// der Name und der Wert müssen in doppelten Anführungszeichen eingeschlossen werden
// einfache Anführungszeichen sind ungültig
$bad_json = "{ 'bar': 'baz' }";
json_decode($bad_json); // null
// der Name muss in doppelten Anführungszeichen eingeschlossen werden
$bad_json = '{ bar: "baz" }';
json_decode($bad_json); // null
// nachfolgende Kommata sind nicht erlaubt
$bad_json = '{ bar: "baz", }';
json_decode($bad_json); // null
?>
Beispiel #4 Fehler bei der Verwendung von depth
<?php
// Daten kodieren
$json = json_encode(
array(
1 => array(
'englisch' => array(
'One',
'January'
),
'französisch' => array(
'Une',
'Janvier'
)
)
)
);
// Errordefinitionen
$json_errors = array(
JSON_ERROR_NONE => 'Es ist kein Fehler aufgetreten',
JSON_ERROR_DEPTH => 'Die maximale Stacktiefe wurde erreicht',
JSON_ERROR_CTRL_CHAR => 'Steuerzeichenfehler, möglicherweise fehlerhaft kodiert',
JSON_ERROR_SYNTAX => 'Syntaxfehler',
);
// Zeige die Fehler für unterschiedliche Verschachtelungstiefen
foreach(range(4, 3, -1) as $depth) {
var_dump(json_decode($json, true, $depth));
echo 'Letzter Fehler : ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL;
}
?>
Das oben gezeigte Beispiel erzeugt folgende Ausgabe:
array(1) {
[1]=>
array(2) {
["English"]=>
array(2) {
[0]=>
string(3) "One"
[1]=>
string(7) "January"
}
["French"]=>
array(2) {
[0]=>
string(3) "Une"
[1]=>
string(7) "Janvier"
}
}
}
Letzter Fehler : Es ist kein Fehler aufgetreten
NULL
Letzter Fehler : Die maximale Stacktiefe wurde erreicht
Anmerkungen
Hinweis:
Die JSON-Spezifikation ist nicht JavaScript, aber ein Subset davon.
Hinweis:
Tritt ein Dekodierungsfehler auf, kann json_last_error() verwendet werden, um die exakte Natur des Fehlers zu ermitteln.
Changelog
| Version | Beschreibung |
|---|---|
| 5.3.0 | Der optionale Parameter depth wurde hinzugefügt. Die Standardrekursionstiefe wurde von 128 auf 512 heraufgesetzt. |
| 5.2.3 | Die Verschachtelungsgrenze wurde von 20 auf 128 angehoben. |
Siehe auch
- json_encode() - Gibt die JSON-Repräsentation eines Wertes zurück
- json_last_error() - Gibt den letzten aufgetretenen Fehler zurück
json_decode
25-May-2007 04:43
22-Apr-2007 06:15
You can't transport Objects or serialize Classes, json_* replace it bei stdClass!
<?php
$dom = new DomDocument( '1.0', 'utf-8' );
$body = $dom->appendChild( $dom->createElement( "body" ) );
$body->appendChild( $dom->createElement( "forward", "Hallo" ) );
$JSON_STRING = json_encode(
array(
"aArray" => range( "a", "z" ),
"bArray" => range( 1, 50 ),
"cArray" => range( 1, 50, 5 ),
"String" => "Value",
"stdClass" => $dom,
"XML" => $dom->saveXML()
)
);
unset( $dom );
$Search = "XML";
$MyStdClass = json_decode( $JSON_STRING );
// var_dump( "<pre>" , $MyStdClass , "</pre>" );
try {
throw new Exception( "$Search isn't a Instance of 'stdClass' Class by json_decode()." );
if ( $MyStdClass->$Search instanceof $MyStdClass )
var_dump( "<pre>instanceof:" , $MyStdClass->$Search , "</pre>" );
} catch( Exception $ErrorHandle ) {
echo $ErrorHandle->getMessage();
if ( property_exists( $MyStdClass, $Search ) ) {
$dom = new DomDocument( "1.0", "utf-8" );
$dom->loadXML( $MyStdClass->$Search );
$body = $dom->getElementsByTagName( "body" )->item(0);
$body->appendChild( $dom->createElement( "rewind", "Nice" ) );
var_dump( htmlentities( $dom->saveXML(), ENT_QUOTES, 'utf-8' ) );
}
}
?>
09-Feb-2007 02:15
I think there is a bug in json_decode() method.
When I try to decode JSON string {"a":"<p>test</p>"} into array on server-side, it fails.
$input='{"a":"<p>test</p>"}';
$input=stripslashes($input);//ro remove slashes if any.
$output=json_decode($input, true);//it fails
<p>, <P> tags should not be in the JSON string.
21-Jan-2007 04:08
I've written a javascript function to get around this functions limitations and the limitations imposed by IE's lack of native support for json serialization. Rather than converting variables to a json formatted string to transfer them to the server this function converts any javascript variable to a string serialized for use as POST or GET data.
String js2php(Mixed);
js2php({foo:true, bar:false, baz: {a:1, b:2, c:[1, 2, 3]}}));
will return:
foo=true&bar=false&baz[a]=1&baz[b]=2&baz[c][0]=1&...etc
function js2php(obj,path,new_path) {
if (typeof(path) == 'undefined') var path=[];
if (typeof(new_path) != 'undefined') path.push(new_path);
var post_str = [];
if (typeof(obj) == 'array' || typeof(obj) == 'object') {
for (var n in obj) {
post_str.push(js2php(obj[n],path,n));
}
}
else if (typeof(obj) != 'function') {
var base = path.shift();
post_str.push(base + (path.length > 0 ? '[' + path.join('][') + ']' : '') + '=' + encodeURI(obj));
path.unshift(base);
}
path.pop();
return post_str.join('&');
}
13-Dec-2006 08:52
Beware when decoding JSON from JavaScript. Almost nobody uses quotes for object property names and none of the major browsers require it, but this function does! {a:1} will decode as NULL, whereas the ugly {"a":1} will decode correctly. Luckily the browsers accept the specification-style quotes as well.
09-Nov-2006 07:11
One of the purpose of JSON is to be easy for humans to read and write. But the output of json_encode() doen't indent very nicely... a "flat" string !
This function might help to have a nice identation :)
<?php
echo indentJson(json_encode($anArray));
function indentJson($str){
$strOut = '';
$identPos = 0;
for($loop = 0;$loop<= strlen($str) ;$loop++){
$_char = substr($str,$loop,1);
//part 1
if($_char == '}' || $_char == ']'){
$strOut .= chr(13);
$identPos --;
for($ident = 0;$ident < $identPos;$ident++){
$strOut .= chr(9);
}
}
//part 2
$strOut .= $_char;
//part 3
if($_char == ',' || $_char == '{' || $_char == '['){
$strOut .= chr(13);
if($_char == '{' || $_char == '[')
$identPos ++;
for($ident = 0;$ident < $identPos;$ident++){
$strOut .= chr(9);
}
}
}
return $strOut;
?>
04-Sep-2006 05:16
Take care that json_decode() returns UTF8 encoded strings, whereas PHP normally works with iso-8859-1 characters.
If you expect to receive json data comprising characters outside the ascii range, be sure to use utf8_decode to convert them:
$php_vlaues = utf8_decode(json_decode($somedata))
04-Sep-2006 12:20
Please note that this function does NOT convert back to PHP values all strings resulting from a call to json-encode.
Since the json spec says that "A JSON text is a serialized object or array", this function will return NULL when decoding any json string that does not represent either an object or an array.
To successfully encode + decode single php values such as strings, booleans, integers or floats, you will have to wrap them in an array before converting them.