A
A
Alexey Kostyukhin2019-05-22 15:09:04
JavaScript
Alexey Kostyukhin, 2019-05-22 15:09:04

How to turn objects with links into JSON?

Good afternoon, How to turn objects with links into JSON?
But without using a third party library?
Turn the team object from the example below into JSON:

var leader = {
  name: "Василий Иванович"
};

var soldier = {
  name: "Петька"
};

// эти объекты ссылаются друг на друга!
leader.soldier = soldier;
soldier.leader = leader;

var team = [leader, soldier];

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
dollar, 2019-05-22
@aleksey4uk

The point is that JSON cannot have circular references by definition. It doesn't even have variables.
Your best bet is to switch to a slightly different data format. Namely, to store not references to objects, but their keys as strings . Such reference strings are easily serialized.

leader.soldier = "soldier";
soldier.leader = "leader";

It is better not to convert automatically, but to take this format as a basis. But if you really want to, then something like this:
for (let key in obj) {
  if (window[key]) obj[key] = key; //любой ваш критерий
}

In the future, for verification, however, a slightly more complicated code will be needed:
var test_leader = soldier.leader && window[soldier.leader];
//Конечно, вместо window у вас будет свой объект-обертка

To get rid of this, you will only need to "repair" the object after JSON.parse

K
kova1ev, 2019-05-22
@kova1ev

I don't understand why people ask such questions.
Task with learn.javascript
You can also see the solution there if you can't think of it yourself. But for some reason the author wants to ask a question on the toaster. Author Why?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question