sarah sarah - 23 days ago 10
CSS Question

turn a text area input string to type object

I have a function that reads the input of a text area.

The input of the text area comes back as a string but i want it to be an object.

How to turn it into an object? i used json.parse and eval. i get errors:
VM16897:1 Uncaught SyntaxError: Unexpected token v in JSON at position 0
at JSON.parse ()

the format i want:

var a = {
"ss": [{
"name": "O",
"id": "shh1",
"url": "hthh.sss"
}]
}],
"Maacks": [{
"name": "Default",
}
}]
}


what i get when i get the textarea input:

"var a = {
"ss": [{
"name": "O",
"id": "shh1",
"url": "hthh.sss"
}]
}],
"Maacks": [{
"name": "Default",
}
}]
}"

Answer

You should type as below without var a = as below. Also, you have to correct your opening and closing braces.

{
                     "ss": [{
                        "name": "O",
                            "id": "shh1",
                            "url": "hthh.sss"
                         }
                    ],
                    "Maacks": [{
                    "name": "Default"
                          }
                     ]
                }

Then parse using JSON.parse as below,

var a = JSON.parse(textArea.value);

Working sample

// Copy the below content inside the commented line (/* ... */) into the text area and click the 'Convert' button,

/*

{
  "ss": [{
                        "name": "O",
                            "id": "shh1",
                            "url": "hthh.sss"
                         }
                    ],
                    "Maacks": [{
                    "name": "Default"
                          }
                     ]
}

*/



function convert() { 
  var jsonText = document.getElementById('textArea').value;
  if(jsonText) {
    try {
      var json = JSON.parse(jsonText);
      console.log(json);
    } catch(e) {
      console.log(e);     
    }
  }
}
<textarea id="textArea" rows="10" cols="50"></textarea>
<br/>
<input type="button" value="Convert" onclick="convert()"/>