Answer the question
In order to leave comments, you need to log in
How to parse json normally?
I work in Redux transpiling code through babel.
I get this line from the server.
{'id': 50, 'text': 'j', 'datetime': '2018-07-04 12:15:56.154427+00:00', 'sender': 'test', 'thread': 1}
// Вот такая конструкция
JSON.constructor({'id': 50, 'text': 'j', 'datetime': '2018-07-04 12:15:56.154427+00:00', 'sender': 'test', 'thread': 1})
//Выдает мне вот это...
String {"{'id': 50, 'text': 'j', 'datetime': '2018-07-04 12…:56.154427+00:00', 'sender': 'test', 'thread': 1}"}
// Вот такой объект я хочу получить, а Js на до мной издевается
{id: 50, text: "j", datetime: "2018-07-04 12:15:56.154427+00:00", sender: "test", thread: 1}
Answer the question
In order to leave comments, you need to log in
It seems that in chrome and node you pass an object (which you threw off) to JSON.constructor, and in your code a string is passed that needs to be turned into an object via JSON.parse
UPD: You have JSON5 format, because you have single quotes. There are a couple of options.
1) Fix the whole thing in eval (not cool).
2) Replace single quotes with double quotes (so-so) using replace.
3) You can use this lib https://github.com/json5/json5 (already better).
4) Knock on the head of the back-end so that it produces normal JSON (ideal).
You don't have valid JSON, without double quotes. It's not even JSON, it's a Javascript object.
You can immediately process the date when parsing by making a date object from the string:
var string = JSON.stringify({'id': 50, 'text': 'j', 'datetime': '2018-07-04 12:15:56.154427+00:00', 'sender': 'test', 'thread': 1});
var object = JSON.parse(string, function(key, value) {
return key === 'datetime' ? new Date(value) : value;
});
here's an option:
const toJSON = {'id': 50, 'text': 'j', 'datetime': '2018-07-04 12:15:56.154427+00:00', 'sender': 'test', 'thread': 1}
console.log(JSON.stringify(toJSON))
const fromJSON = JSON.stringify(toJSON)
console.log(JSON.parse(fromJSON))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question