6

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\":\"\"}]""
2
  • 1
    I'd answer "apply JSON.parse twice" ... but obviously, the best thing you can do is find where stringify is applied twice Commented Jul 27, 2015 at 20:43
  • not work i try it tanx any way Commented Jul 27, 2015 at 20:52

2 Answers 2

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;
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

tanx but every time i trace to debug it its not problem and every thing is perfect and i can not parse it becuse its not now it as object to parse
@Pooria.Shariatzadeh I just added an edit that might help your debugging
it is helpful but my problem is that I don't no when my program is buged I mean I try over 30 time to debug it but every time its work without problem but install program on server has this problem just tow time in over 60 record that saved in db so I don't now what is the problem or where I most look
0

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.

Comments

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.