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:"Vasily Ivanovich"

var soldier={

//these objects link to each other!

var team=[leader, soldier];
  • No.

    Determine how you want to store circular references in JSON and write the appropriate code.
    – Hungry5 May 22 '19 at 15:21

3 Answers 3

The fact is that in JSON there can be no circular references by definition.There are not even variables.

The best thing is for you to switch to a slightly different data format.Namely, do not store links to objects, but their keys as strings.Such strings-links are quietly serialized.

It is better not to convert automatically, but to take such a format as a basis.But if you really want it, then something like this:
for(let key in obj) {
  if(window[key]) obj[key]=key;//any of your criteria

In the future, for verification, however, we will need a little more complicated code:
var test_leader=soldier.leader&window&[soldier.leader];
//Of course, instead of window you will have your own wrapper object

To get rid of this you only need to"repair" the object after JSON.parse
I do not understand why they ask such questions.

A challenge with learn.javascript

In the same place you can see the solution if you can’t think of it yourself.But for some reason the author wants to ask a question on a toaster.The author, why?