-3

I have JSON data like this -

var json = {
 "details": [
   {
  "A": {
   "Name": "mike",
   "Age": 22
  },
  "B": {
   "Name": "John",
   "Age": 25
  }
 }
 ]
}

I want to read A,B points as an array.

Ashish
  • 85
  • 1
  • 2
  • 14
  • How to access json object -> https://stackoverflow.com/questions/10895306/how-to-access-json-object-name-value – Jixone Aug 15 '17 at 05:56
  • 2
    You surely have a piece of code we can help you to improve. We will not write your code. – Zim84 Aug 15 '17 at 05:56
  • I have small where I am just parsing the variable which created for json. – Ashish Aug 15 '17 at 06:36

3 Answers3

2

Another way to do it with your json, Object.keys(),since your options are not in array form, can use that to convert to array form.

var json = {
 "details": [
   {
  "A": {
   "Name": "mike",
   "Age": 22
  },
  "B": {
   "Name": "John",
   "Age": 25
  }
 }
 ]
}

var outputDiv = document.getElementById('output');

var options = Object.keys(json.details[0]).map(function(item){
  return '<option value="'+item+'">'+ item +'</option>'
})
options.unshift('<option value="" > Please select </option>')
var select = document.getElementById('your_options');
select.innerHTML = options.join()
select.onchange = function() {
  outputDiv.innerHTML = JSON.stringify(json.details[0][this.value]);
}
<label>You options</label>
<select id="your_options">
</select>

<div id="output"></div>
Mosd
  • 1,640
  • 19
  • 22
1

Lets assume you receive the following JSON from a web server

'{ "firstName":"Foo", "lastName":"Bar" }'

To access this data you first need to parse the raw JSON and form a Javascript object

let response = JSON.parse('{ "firstName":"Foo", "lastName":"Bar" }');

This forms an object which we can access relativly simply

let firstName = response["firstName"];
let lastName = response["lastName"];
0

Have a look at javascript documentation regarding JSON: http://devdocs.io/javascript-json/

Examples:

JSON.parse('{}');              // {}
JSON.parse('true');            // true
JSON.parse('"foo"');           // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null');            // null
Gertsen
  • 1,078
  • 20
  • 36