1

i try to json strigify and parse after circular structure. I want to pass to all my website my variable socket when i use socket io. In React, it's easy but the project is old and they not use React for all the project.

I use flatted library, and it's work very good for stringify but i don't get my original element. When i parse it, i get an object

const mySocket = io("monsite:1234");
const stringigy = JSON.stringify(mySocket);
localStorage.setItem("io",mySocket);

don't work because circular structure.

With Flatted

const mySocket = io("monsite:1234");
const stringigy = Flatted.stringify(mySocket);
localStorage.setItem("io",mySocket);

work but when i parse, i don't get the original value

socket = Flatted.parse(getIo);

EDIT: Flatted

Thanks for help.

3
  • 2
    It's inherently impossible to serialize a data structure that contains cycles to a format like JSON. If you flatten it, you're of course changing the structure. Commented Sep 5, 2019 at 14:52
  • 2
    why are you trying to serialize a socket? Commented Sep 5, 2019 at 14:52
  • because i want pass the socket that i create in all my website Commented Sep 5, 2019 at 15:24

1 Answer 1

6

A Circular structure is when a property of the object is the object itself directly (a -> a) or indirectly (a -> b -> a).

To avoid the error message, tell JSON.stringify what to do with circular reference.

The second parameter to stringify is a filter function. Here it simply converts the referred object to its ID, but you are free to do whatever you like to break the circular reference.

For example, if you have a person pointing to another person ("father"), which may (or may not) point to the original person, do the following:

JSON.stringify( that.person, function( key, value) {
  if( key == 'father') { return value.id;}
  else {return value;}
})
Sign up to request clarification or add additional context in comments.

5 Comments

@Khol if you want to re-create the circular references, you'll have to come up with some annotation scheme to indicate what has to be done. It is impossible to serialize to JSON a circular structure, so any serialization inherently must change the structure.
If you don't know the readability of the stringified object, I suggest using CircularJSON.
But In fact, why do you want to stringify a socket?
i want to stringify it to put it in local storage like i say in my thread. I want my variable pass in all my website.
i use flatted, the new version of CircularJSON. i will update my thread with picture what i get when i parse after stringify

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.