I'd hate to open a new question even though many questions have been opened on this same topic, but I'm literally at my ends as to why this isn't working.
I am attempting to create a JSON object with the following code:
var p = JSON.stringify(decodeJSON('{{post.as_json}}'))
var post = JSON.parse(p);
console.log(post); // Debug log to test if code is valid
And the decodeJSON function:
function decodeJSON(json) {
var txt = document.createElement("textarea");
txt.innerHTML = json;
return txt.value.replace(/u'/g, "'");
}
console.log(post) returns the following JSON string:
{'content': 'kj fasf', 'uid': '4eL1BQ__', 'created': '07/09/2017', 'replies': [], 'tags': ['python'], 'by': {'username': 'Dorian', 'img_url': '/static/imgs/user_Dorian/beaut.jpg'}, 'likes': 0}
After scanning through the string I am pretty sure that the JSON is valid and there are no syntax errors. However, when running JSON.parse(p) Instead of receiving an object, I get a string back. What could be the cause?
That's because decodeJSON returns a string, and JSON.stringify turns that string in another string.
In the other hand, you used JSON.strigify() method on a string. You should stringify an object, not string.
JSON.stringify() turns a javascript object to json text and stores it in a string.
When you use JSON.parse you obtain the string returned by decodedJSON function, not object.
Solution:
var p = JSON.stringify('{{post.as_json}}');
var post = JSON.parse(p);
console.log(post);
It gives me Uncaught SyntaxError: Unexpected token ' in JSON at position 1
The solution is to modify your decodeJSON method.
function decodeJSON(json) {
var txt = document.createElement("textarea");
txt.innerHTML = json;
return txt.value.replace(/u'/g, '\"');
}
var p = decodeJSON('{{post.as_json}}');
var post = JSON.parse(p);
console.log(post);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With