3

I have a div which outputs as text a json format:

HTML

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

JS

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

That gives me:

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

Now I need to set that as a variable to be able to read it and this is what I am doing but I get nothing at all:

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

I am trying to have the output like:

var root = {
 "name": "flare",
 "url": "http://google.com",
 "children": [
   {
     "name": "an...
rob.m
  • 9,843
  • 19
  • 73
  • 162

1 Answers1

3

If you're trying to create an object out of the JSON string, seek 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>
vol7ron
  • 40,809
  • 21
  • 119
  • 172