X
X
Xaip2018-07-04 15:21:32
JavaScript
Xaip, 2018-07-04 15:21:32

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}

It would seem... A trivial task JSON.constructor() and that's it, but no.
// Вот такая конструкция
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}"}

Although in the console of node and chrome a normal object is issued:
// Вот такой объект я хочу получить, а 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

3 answer(s)
V
Vladimir Proskurin, 2018-07-04
@Xaip

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).

I
Ihor Bratukh, 2018-07-04
@BRAGA96

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;
});

G
Gaba-Zhaba, 2022-03-19
@Gaba-Zhaba

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 question

Ask a Question

731 491 924 answers to any question