45
{"document":
  {"people":[
    {"name":["Harry Potter"],"age":["18"],"gender":["Male"]},
    {"name":["hermione granger"],"age":["18"],"gender":["Female"]},
  ]}
}

From this JSON example, I would like to get the keys such as name, age, gender for each people.

How to do this?

2
  • 12
    Your JSON structure is incorrect. Name, age, and gender should be single properties, not lists. It should be {"name": "Harry Potter", "age":"18", "gender":"Male"} (no square brackets). Commented Nov 13, 2014 at 5:50
  • This has nothing to do with JSON, which is just a text format. Commented Jan 17, 2020 at 22:43

7 Answers 7

93

I use Object.keys which is built into JavaScript Object, it will return an array of keys from given object MDN Reference

const person = {
  name: "Jeeva",
  age: "22",
  gender: "Male"
}
console.log(Object.keys(person))

Sign up to request clarification or add additional context in comments.

3 Comments

This isn't the correct solution to what was asked. All you did was simplify the problem and solve that, which won't be of any help
Oh sorry, I am new to answering questions. I will keep that in mind next time
FWIW: the accepted solution also doesn't answer the question.
52

Try this

var s = {name: "raul", age: "22", gender: "Male"}
   var keys = [];
   for(var k in s) keys.push(k);

Here keys array will return your keys ["name", "age", "gender"]

3 Comments

Can we have a generic solution. Like working for this: var object3 = { parent1: 42, parent2: [13, 12, { 'child1': 222 }], parent3: { child1: 44, child2: "ok", child3: [44, 45, 47, 48] }, parent4: { child1: 444 } };
how can we return all keys in nested objects and arrays? like getting all keys from "data":{ "user":{ "id": 1, "name": "xyz" }, "address":[ "street":"xyz", "location: "xxx"] }
@NisrineBouGhannam did you ever find a solution for this question - I am wondering the same thing.
18
var input = {"document":
  {"people":[
    {"name":["Harry Potter"],"age":["18"],"gender":["Male"]},
    {"name":["hermione granger"],"age":["18"],"gender":["Female"]},
  ]}
}

var keys = [];
for(var i = 0;i<input.document.people.length;i++)
{
    Object.keys(input.document.people[i]).forEach(function(key){
        if(keys.indexOf(key) == -1)
        {
            keys.push(key);
        }
    });
}
console.log(keys);

6 Comments

Object.keys called on non-object can be here, if people is empty array
I think your first version was a best answer, need only check array isn't empty. Current version is too complicated :)
This is a good solution, and prevents the same keys from being added more than once
@vp_arth Actually, that would work only for the first item in the array, say if the second or third object have some extra properties like "address", it would have failed.
It is other task with some other conditions, may be need to get only common fields of all entities.
|
8

ES6 of the day here;

const json_getAllKeys = data => (
  data.reduce((keys, obj) => (
    keys.concat(Object.keys(obj).filter(key => (
      keys.indexOf(key) === -1))
    )
  ), [])
)

And yes it can be written in very long one line;

const json_getAllKeys = data => data.reduce((keys, obj) => keys.concat(Object.keys(obj).filter(key => keys.indexOf(key) === -1)), [])

EDIT: Returns all first order keys if the input is of type array of objects

Comments

5

This function should return an array of ALL the keys (i.e. the key names) in a JSON object including nested key/value pairs.

function get_all_json_keys(json_object, ret_array = []) {
    for (json_key in json_object) {
        if (typeof(json_object[json_key]) === 'object' && !Array.isArray(json_object[json_key])) {
            ret_array.push(json_key);
            get_all_json_keys(json_object[json_key], ret_array);
        } else if (Array.isArray(json_object[json_key])) {
            ret_array.push(json_key);
            first_element = json_object[json_key][0];
            if (typeof(first_element) === 'object') {
                get_all_json_keys(first_element, ret_array);
            }
        } else {
            ret_array.push(json_key);
        }
    }

    return ret_array
}

Using this function on the OP's original object

const op_object =
{
    "document":{
       "people":[
          {
             "name":[
                "Harry Potter"
             ],
             "age":[
                "18"
             ],
             "gender":[
                "Male"
             ]
          },
          {
             "name":[
                "hermione granger"
             ],
             "age":[
                "18"
             ],
             "gender":[
                "Female"
             ]
          }
       ]
    }
 }

var all_keys = [];

function get_all_json_keys(json_object, ret_array = []) {
    for (json_key in json_object) {
        if (typeof(json_object[json_key]) === 'object' && !Array.isArray(json_object[json_key])) {
            ret_array.push(json_key);
            get_all_json_keys(json_object[json_key], ret_array);
        } else if (Array.isArray(json_object[json_key])) {
            ret_array.push(json_key);
            first_element = json_object[json_key][0];
            if (typeof(first_element) === 'object') {
                get_all_json_keys(first_element, ret_array);
            }
        } else {
            ret_array.push(json_key);
        }
    }

    return ret_array
}

get_all_json_keys(op_object, all_keys);

console.log(all_keys);

should yield

[ 'document', 'people', 'name', 'age', 'gender' ]

Note: This will return a unique list of all key names.

Comments

3
var jsonData = { Name: "Ricardo Vasquez", age: "46", Email: "[email protected]" };

for (x in jsonData) {   
  console.log(x +" => "+ jsonData[x]);  
  alert(x +" => "+  jsonData[x]);  
  }

1 Comment

While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.
0

We must "parse" our jsonObject

 console.log('{"key0":"value0", "key1":"value1"}'); 
    var jsonObject = JSON.parse('{"key0":"value0", "key1":"value1"}')
    Object.keys(jsonObject).forEach(key => { 
        console.log(jsonObject[key]); //values 
        console.log(key); //keys 
    })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.