最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - json_encode adding unwanted slashes - Stack Overflow

programmeradmin2浏览0评论

I have a json string saved in my db. When i retrieve it from db to pass it to the javascript function (ajax call) , along with the id of that row, i am json_encoding both (the query result array) and passing it to js. but json_encode is adding unwanted slashes to my already json string. how to escape it. remember i have to pass the id also as second element in array.

my json string in db is like:

{"field":"City","term":"Hawaiian Gardens, CA"}

and the id is say 5.

so the query result array in PHP is:

$savedVal['id'] = 5 
$savedVal['object_str'] = {"field":"City","term":"Hawaiian Gardens, CA"}

so after json_encode($savedVal) ideally it should be:

{"id":"5","object_str":{"field":"City","term":"Hawaiian Gardens, CA"}}

but json_encoding the array gives me:

{"id":"5","object_str":"{\"field\":\"City\",\"term\":\"Hawaiian Gardens, CA\"}}

extra slashes and quotes too around object_str value. Please help me.

Thank you.

I have a json string saved in my db. When i retrieve it from db to pass it to the javascript function (ajax call) , along with the id of that row, i am json_encoding both (the query result array) and passing it to js. but json_encode is adding unwanted slashes to my already json string. how to escape it. remember i have to pass the id also as second element in array.

my json string in db is like:

{"field":"City","term":"Hawaiian Gardens, CA"}

and the id is say 5.

so the query result array in PHP is:

$savedVal['id'] = 5 
$savedVal['object_str'] = {"field":"City","term":"Hawaiian Gardens, CA"}

so after json_encode($savedVal) ideally it should be:

{"id":"5","object_str":{"field":"City","term":"Hawaiian Gardens, CA"}}

but json_encoding the array gives me:

{"id":"5","object_str":"{\"field\":\"City\",\"term\":\"Hawaiian Gardens, CA\"}}

extra slashes and quotes too around object_str value. Please help me.

Thank you.

Share Improve this question edited Jun 17, 2011 at 16:58 Programmer Bruce 66.9k7 gold badges100 silver badges97 bronze badges asked Mar 11, 2010 at 14:10 PrashantPrashant 5,46110 gold badges46 silver badges59 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 21

You are running JSON_encode on JSON - this is why the double escaping occurs. Try this:

$savedVal['id'] = 5 ;
$savedVal['object_str'] = json_decode( '{"field":"City","term":"Hawaiian Gardens, CA"}' );

echo json_encode( $savedVal );

Output

{"id":5,"object_str":{"field":"City","term":"Hawaiian Gardens, CA"}}
发布评论

评论列表(0)

  1. 暂无评论