nikhil rao
nikhil rao

Reputation: 381

Getting JSON data from text area

In the fiddle - http://jsfiddle.net/660m7g7k/

<textarea id="input">
[
{
  name: "Tyorry",
  age: 22
}, {
  name: "greg",
 age: 44
}, {
  name: "aff",
  age: 99
}, {
  name: "ben",
  age: 20
}
]

var x=document.getElementById("input").value;
alert(x[0]);

There is JSON data, array of objects basically. I have 2 questions.

1) Is this JSON data in JSON.stringify format or JSON.parse format? since JSON.parse is erroring out and JSON.stringify is working properly.

2) Am getting the JSON data from textarea. but x[0] or x[3] is returning blank. basically i want to loop through the array item(which are objects) and get the values, name and age.

Upvotes: 1

Views: 6326

Answers (2)

bhantol
bhantol

Reputation: 9616

In Plain JS use this

var x=document.getElementById("input").value;
var y = eval(x);
alert('hi '+y[0].name+ ' are you '+ y[0].age+' years old');

Plunker

Upvotes: 1

DLeh
DLeh

Reputation: 24395

The value in a text area is always a string. So if you want it as an object you'll want to use JSON.parse() to get it. If JSON.Parse() is failing then your JSON is in an invalid format.

To check if your JSON is valid, try using something like http://jsonlint.com/. The JSON provived in the fiddle is invalid.

Upvotes: 3

Related Questions