Get JSON Object value without knowing key names

Get JSON Object value without knowing key names or How to accessing elements of JSON object without knowing key names. Parse JSON get value from structure in JavaScript. Here is solution for get JSON Object value without knowing key.

For accessing any element of JSON object, Object key is must. If we not have key name we not able to access JSON element from Object structure.

Before provide solution let us check more detail for JSON object.

What is JSON (JavaScript Object Notation)

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition – December 1999.

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

Here we check solution for first type of JSON structure. A collection of name/value pairs.

Object.keys()

Object.keys() returns an array whose elements are strings corresponding to the enumerable properties found directly upon object. The ordering of the properties is the same as that given by looping over the properties of the object manually.

// array like object with random key ordering
var anObj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.keys(anObj)); // ['2', '7', '100']

Solution and Example for Get JSON Object value without knowing key names

Solution step is simple, Below is step by step process for Get JSON Object value by just knowing index of element.

  1. Get all keys name array from JSON Object using Object.keys()
  2. Decide which index value to get
  3. Access Object element value using keys array
var obj = { first: 'someVal', second: 'anotherVal' };
obj[Object.keys(obj)[1]]; //anotherVal

In above solution, If you want to get value of second element in object without knowing key name of second element. Now as per solution steps get keys array and by using array we can access any element by just providing index.