admin管理员组

文章数量:1221420

How can i parse some object that stringify twice?

Most of the time in my code it is not problem but some times it stringify twice, and I can not trace the code to find my problem.

My JSON object something like this:

""[{\"name\":\"trane\",\"price\":\"150000\",\"order\":\"\",\"sale\":\"\",\"printedPic\":\"\",\"remainingPic\":\"\",\"locationEncome\":\"\"}]""

How can i parse some object that stringify twice?

Most of the time in my code it is not problem but some times it stringify twice, and I can not trace the code to find my problem.

My JSON object something like this:

""[{\"name\":\"trane\",\"price\":\"150000\",\"order\":\"\",\"sale\":\"\",\"printedPic\":\"\",\"remainingPic\":\"\",\"locationEncome\":\"\"}]""
Share Improve this question edited May 5, 2020 at 14:01 d-_-b 23.2k43 gold badges171 silver badges282 bronze badges asked Jul 27, 2015 at 20:38 Pooria.ShariatzadehPooria.Shariatzadeh 3012 gold badges4 silver badges16 bronze badges 2
  • 1 I'd answer "apply JSON.parse twice" ... but obviously, the best thing you can do is find where stringify is applied twice – leo.fcx Commented Jul 27, 2015 at 20:43
  • not work i try it tanx any way – Pooria.Shariatzadeh Commented Jul 27, 2015 at 20:52
Add a comment  | 

2 Answers 2

Reset to default 16

It's definitely best to figure out where and why it's stringifying twice, but you can just parse twice if you have to.

JSON.parse(JSON.parse("JSON STRING HERE"))

Edit

Potentially you're stringifying an already stringified object, this could help you figure out what is going wrong.

Add this function to your code and then replace your JSON.stringify calls to JSON.stringifyIfObject calls. Just use this as a means of debugging though, I wouldn't put this into production.

JSON.stringifyIfObject = function stringifyIfObject(obj){
    if(typeof obj == "object")
        return JSON.stringify(obj);
    else{
        alert("found already stringified object")
        return obj;
    }
}

This post is a little bit old but I had the same problem today and it was caused by a third party library.

Javascript library Prototype.js applies JSON.stringify() twice when it is used in version 1.6.x (it seems that this bug was removed in version 1.7)

The following code :

var test = ["banana"];
JSON.stringify(test);

will give you the following result :

""[\"banana\"]""

instead of (normally expected) :

"["banana"]"

Here is my source : https://github.com/krinkle/jquery-json/issues/35

If that happens to you, the best option is to upgrade that library if you can.

本文标签: javascriptparse json object That stringify TwiceStack Overflow