如何将div的文本作为json字符串放置?

时间:2017-03-27 18:47:39

标签: javascript jquery json

我有一个以文本形式输出json格式的div:

HTML

<div id="myMap"></div>

JS

$('#myMap').text(JSON.stringify(out[0], null, 2));

这让我:

{ "name": "Leopardi", "children": [ { "name": "Vita", "children": [ { "name": "Ubriacone" } ] }, { "name": "Poesie", "children": [ { "name": "L'infinito" } ] } ] }

现在我需要将其设置为一个变量才能读取它,这就是我正在做的但是我什么都没得到:

var root =  $('#myMap').text();

我正在尝试输出:

var root = {
 "name": "flare",
 "url": "http://google.com",
 "children": [
   {
     "name": "an...

1 个答案:

答案 0 :(得分:3)

如果您尝试使用JSON字符串创建对象,请搜索JSON.parse()

var out = [{
  "name": "Leopardi",
  "children": [{
    "name": "Vita",
    "children": [{
      "name": "Ubriacone"
    }]
  }, {
    "name": "Poesie",
    "children": [{
      "name": "L'infinito"
    }]
  }]
}];

$('#myMap').text(JSON.stringify(out[0], null, 2));

var root = JSON.parse( $('#myMap').text() ); // <-- JSON.parse

console.log('root.name:', root.name);        // <-- can treat 'root' as object
#myMap {
  border: 1px solid;
  padding: .5em;
  font-family: monospace;
  white-space: pre;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

MyMap:
<div id="myMap"></div>