Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

php - Why is json_encode adding backslashes?

I've been using json_encode for a long time, and I've not had any problems so far. Now I'm working with a upload script and I try to return some JSON data after file upload.

I have the following code:

print_r($result); // <-- This is an associative array
echo json_encode($result); // <-- this returns valid JSON

This gives me the following results:

// print_r result
Array
(
    [logo_url] => http://mysite.com/uploads/gallery/7f/3b/f65ab8165d_logo.jpeg
    [img_id] => 54
    [feedback] => Array
        (
            [message] => File uploaded
            [success] => 1
        )

)

// Echo result
{"logo_url":"http://mysite.com/uploads/gallery/7f/3b/f65ab8165d_logo.jpeg","img_id":"54","feedback":{"message":"File uploaded","success":true}}

Can anyone tell me why json_encode adds slashes?

update

@Quentin said that something is happening between json_encode and .parseJSON and he's right.

Doing a alert(data.toSource()); gives me the dollowing result:

({response:"{"logo_url":"http:\/\/storelocator.com\/wp-content\/uploads\/gallery\/7f\/3b\/71b9520cfc91a90afbdbbfc9d2b2239b_logo.jpeg","img_id":"62","feedback":{"message":"File uploaded","success":true}}", status:200})

And this is not valid JSON. It also adds the status:200 and I have no idea where this comes from.

Could it be that the Plupload bind does something to my returned data?

This is my js script:

  uploader.bind('FileUploaded', function(up, file, data) {
    alert(data.toSource());
    $('#' + file.id + " b").html("100%");
  });
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just use the "JSON_UNESCAPED_SLASHES" Option (added after version 5.4).

json_encode($array,JSON_UNESCAPED_SLASHES);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...