-1

Hot to get in JavaScript key-value pairs if the JSON file looks like this:

 [[{"field":"name","message":"Insert name!"},{"field":"surname","message":"Inseerts     
 urname!"},{"field":"email","message":"Insert email"}]];

Current solution returns me one object like Object object Object object Object object and so on.

Code:

 var result = jQuery.parseJSON(data);
 var json_text = JSON.stringify(result, null, null);

1 Answers1

2

I think you are confusing the concepts. There is a difference between a STRING that contains JSON data, such as this:

var json = '[[{"field":"name","message":"Insert name!"},{"field":"surname","message":"Inseertssurname!"},{"field":"email","message":"Insert email"}]]';

and an OBJECT that contains JSON data, such as this:

var data = [[{"field":"name","message":"Insert name!"},{"field":"surname","message":"Inseertsurname!"},{"field":"email","message":"Insert email"}]];

The former you have to parse (for example with JSON.parse or jQuery.parseJSON) which turns it into the latter, which you can then access directly in your script (JSON = JavaScript Object Notation).

Your data is a double-nested list of objects and can be accessed as such:

console.log(data[0][1].field);
data[0].forEach(function (obj) { console.log(obj.field + ': ' + obj.message); });

(List are objects too (typeof [] === 'object') but a special case, see the answer Igor already suggested).

If you are retrieving the data with a library, you often get your data as an object ready to access, if in doubt try:

typeof data // 'string' or 'object' ?
tobi
  • 789
  • 7
  • 10