最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Object to string, and vice-versa - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question edited Sep 14, 2015 at 0:08 peterh 1 asked Sep 13, 2015 at 22:16 FuzzyzillaFuzzyzilla 3564 silver badges15 bronze badges 6
  • 2 JSON.stringify() is your friend! – Ram Commented Sep 13, 2015 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 Commented Sep 13, 2015 at 23:41
  • @Vohuman You made a bad decision, next time please be more careful with your close votes. – peterh Commented Sep 14, 2015 at 0:07
  • What makes it "bad"? Since the question has 3 open votes I'll reopen it! – Ram Commented Sep 14, 2015 at 0: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 Commented Sep 14, 2015 at 0:16
 |  Show 1 more ment

1 Answer 1

Reset to default 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);

发布评论

评论列表(0)

  1. 暂无评论