2

Is there a solution to prevent json_encode adding escape characters? I am returning a json obj from an ajax request.

Here is what I currently have:

foreach ($files as $file)
{
    $inf    =   getimagesize( $file );

    $farr[] = array (
                    "imgurl"    =>  "/".str_replace( "\\" , "/" , str_replace( DOCROOT , "" , $file ) ) ,
                    "width"     =>  $inf[0] ,
                    "height"    =>  $inf[1]
                    );
}
$t  =   json_encode( $farr );

which delivers:

[
{\"imgurl\":\"\\\/_assets\\\/portfolio\\\/96\\\/full.png\",\"width\":580,\"height\":384},
{\"imgurl\":\"\\\/_assets\\\/portfolio\\\/95\\\/full.png\",\"width\":580,\"height\":452},
{\"imgurl\":\"\\\/_assets\\\/portfolio\\\/94\\\/full.png\",\"width\":580,\"height\":384}
]

but I need:

[
{imgurl:"/_assets/portfolio/96/full.png",width:580,height:384},
{imgurl:"/_assets/portfolio/95/full.png",width:580,height:452},
{imgurl:"/_assets/portfolio/94/full.png",width:580,height:384}
]

having the imgurl width and height indexes quoted is causing the rest of my javascript to break

not having much luck so any tips very much welcome...

3
  • 3
    json_encode() does the right thing. This means you must be doing something wrong. Please show the code that breaks. Commented May 19, 2011 at 15:23
  • The output you want is a Javascript expression, not a JSON serialization. There is however one round of addslashes too much in your output, and json_encode doesn't do this. Commented May 19, 2011 at 15:31
  • the jquery is pastie.org/1927196 the error occurs on .attr('src', json[i][indx]) which is undefined... Commented May 19, 2011 at 15:32

1 Answer 1

5

Using the code you have in your question and var_dumping it, I get the following: string(40) "[{"imgurl":"\/bla"},{"imgurl":"\/blub"}]"

Only if I double the json_encode like $t = json_encode(json_encode($farr)); I get the same result as you - so there must be a second json_encode somewhere…

Sign up to request clarification or add additional context in comments.

3 Comments

D'oh - was encoding in the method which returns result to ajaxs script which inturn json_encodes results.... Should a rubber duck debugged that one - srry peeps... ;P
the essential part "Only if I double the json_encode"
Forward slashes in urls will still get escaped, but you can use a FLAG to prevent those, like: json_encode( $response, JSON_UNESCAPED_SLASHES )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.