Shamoon
Shamoon

Reputation: 43491

Does json_encode add additional quotes?

http://codepad.org/zmsXbqhu

I have very simple code (viewable above):

<?php
$js = json_encode( "HO" );
var_dump( $js );
?>

It returns a string with extra quotes around it:

string(4) ""HO""

Any idea why that is?

Upvotes: 1

Views: 6720

Answers (3)

Tadeck
Tadeck

Reputation: 137310

If you do it like that:

$json = json_encode("HO");
echo $json;

it will return the following:

"HO"

The reason your code returns something like that:

string(4) ""HO""

is that you used var_dump(), which can not be treaten as echo's replacement (see var_dump() documentation).

Upvotes: 2

Layke
Layke

Reputation: 53126

Because you are var_dump'ing. It wraps it in the quotes. If you don't var_dump and echo you will see the actual string.

Here, take a look at this:

http://codepad.viper-7.com/KB5Fkk

Code

 <?php

$js = json_encode( '{ book : "how to use json", author: "some clever guy" }' );
var_dump( $js );

echo "<br /> The actual string:<br />";
echo $js;
?>

Output:

string(61) ""{ book : \"how to use json\", author: \"some clever guy\" }"" 
The actual string:
"{ book : \"how to use json\", author: \"some clever guy\" }"

Upvotes: 6

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798526

In JSON...

A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes.

source

Upvotes: 2

Related Questions