0

I have the function below to "clone" an object. Occasionally we see an "Invalid character" error message displayed in the browser's console. Based on the documentation for the JSON object, this function should work flawlessly. I also checked, and the objects being serialized do not implement the toJSON() function. What kind of object(s) would cause this error?

function deepCopy (obj) {
    return JSON.parse(JSON.stringify(obj));
}

Update: It appears to only happen with IE11.

10
  • If you want to parse to json use only JSON.parse no need of JSON.stringify Commented Dec 16, 2016 at 5:11
  • what is the value of obj? Commented Dec 16, 2016 at 5:12
  • What is the most efficient way to deep clone an object in JavaScript? Commented Dec 16, 2016 at 5:13
  • Do you have dates in that object? Commented Dec 16, 2016 at 5:14
  • 2
    JSON.stringify(undefined) returns undefined instead of a string. That might be it. Commented Dec 16, 2016 at 5:32

2 Answers 2

1

JSON.stringify(undefined) returns undefined instead of the string "undefined". As seen on MDN:

JSON.stringify can also just return undefined when passing in "pure" values like JSON.stringify(function(){}) or JSON.stringify(undefined).

JSON.parse has some unclear error messages when it receives a non-serializable object because it will try to convert this object into a string first. I once lost a lot of time on this one in Chrome : Unexpected token u in JSON at position 0.

That's because u is the first letter of undefined converted to a string. A similar error comes up when trying to parse an object, which gives the string "[object Object]" with a valid opening bracket but an unexpected token o afterward. It's good to keep those cases in mind.

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

Comments

0

yes, it happens if the value contains ' character.

So, please clean especial character, another way is converting into utf-8, before stringify.

That way, I solved my problem earlier.

3 Comments

Which way would you recommend converting to "utf-8"?
what is the value of obj?
suppose var a = {}; a = {key: "val'ue"} either you can remove ' from val'ue or you can convert the value, function encode_utf8(s) { return unescape(encodeURIComponent(s)); } //decode function decode_utf8(s) { return decodeURIComponent(escape(s)); }

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.