3

Say I had the object:

var object = {
    1: [2,5,"hi"],
    hi: {hihi: 1}
};

How would I convert that to a string, and then back, preserving all the information? I would need this to work for a big object, with the values themselves being objects.

This is not a duplicate, the others didn't involve getting the object back.

peterh
  • 11,875
  • 18
  • 85
  • 108
Fuzzyzilla
  • 356
  • 4
  • 15
  • 2
    [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) is your friend! – Ram Sep 13 '15 at 22:18
  • 1
    Voting to reopen as not a duplicate because the supposed duplicate is about converting an object to a string, and this question is about how to convert and then retrieve. None of the answers in the duplicate mention `JSON.parse()`, which is an important part of the answer to this question. – Maximillian Laumeister Sep 13 '15 at 23:41
  • @Vohuman You made a bad decision, next time please be more careful with your close votes. – peterh Sep 14 '15 at 00:07
  • What makes it "bad"? Since the question has 3 open votes I'll reopen it! – Ram Sep 14 '15 at 00:16
  • @Vohuman He wanted a 2-way conversion, while the dupe was only unidirectional. Thank you the reopening, and that you'd hear us. – peterh Sep 14 '15 at 00:16
  • "I do not enlighten those who are not eager to learn, nor arouse those who are not anxious to give an explanation themselves. If I have presented one corner of the square and they cannot come back to me with the other three, I should not go over the points again." – Confucius – Ram Sep 14 '15 at 00:22

1 Answers1

7

Below is a live demo of how you can convert an object to a string and back using JSON.stringify() and JSON.parse().

Open your browser console and you can see that all attributes are preserved after the conversion to a string and back.

var object = {
    1: [2,5,"hi"],
    hi: {hihi: 1}
};

console.log(object);

var strobj = JSON.stringify(object);

console.log(strobj);

var unstrobj = JSON.parse(strobj);

console.log(unstrobj);
Maximillian Laumeister
  • 19,884
  • 8
  • 59
  • 78