0

I receive the following JSON as a response

{
                "user_details": [
                {
                        "Name": "Mark"
                },
                {
                        "Age": "35"
                },
                {
                        "Gender": "Male"
                },
                {
                        "Country": "US"
                }]
}

I am parsing this JSON as shown below

 var ajaxresponse = response.user_details;
        if (ajaxresponse.length > 0)
        {
                var Name = ajaxresponse[0].Name;
                var Age = ajaxresponse[1].Age;
                var Gender = ajaxresponse[2].Gender;
                var Country = ajaxresponse[3].Country;
                console.log(Name);
        }

This is working fine .

My question is , if any one of the key is missing in the JSON for example "Name" is missing , its breaking and i am getting undefined

Is it possible to check if exists and then retrive ?

https://jsfiddle.net/o2gxgz9r/9078/

With respect to the answers i modified my json to

{
                "user_details": [
                {
                     "Name": "Mark",
                        "Age": "35",
                        "Gender": "Male",
                        "Country": "US"
                        }
              ]
        }

But hasOwnProperty is not working ?

please see this fiddle

https://jsfiddle.net/o2gxgz9r/9085/

Pawan
  • 28,159
  • 84
  • 232
  • 394
  • maybe [this answers your question](https://stackoverflow.com/questions/20804163/check-if-a-key-exists-inside-a-json-object) – Foo Bar Jun 22 '17 at 10:15
  • You need to refactor that JSON. The array inside `user_details` is unnecessary, and makes it impossible to predict the array index for a given field name (if "Name" is missing, all the rest shift down.) Just make that a plain old object. – Daniel Beck Jun 22 '17 at 10:38
  • Re the update: that's better, but the array is still unnecessary! Just use a plain object, like `"user_details": { "Name": "Mark", "Age": "35" }` – Daniel Beck Jun 22 '17 at 10:42

4 Answers4

2

Firstly this is a wrong way to send data as a response from whatever source it is coming.

Ideal way should be an object map or a vector as given below:

user_details: {
   name: "Mark",
   age: 35,
   gender: "male",
   country: "USA"
}

Secondly, if you want a solution for the data structure you are getting, you will have to actually traverse the array for each item and see if a property exists on it or not.

var arr = ajaxResponse;

var name,age,country,age;

arr.forEach(function(item){
    if(item.hasOwnProperty('name')){
        name = item.name
    }
    //similarly for other objects in the array
));
Rahul Arora
  • 4,217
  • 1
  • 14
  • 22
  • i changed my JSON structure , but why hasOwnProperty is not working ?https://jsfiddle.net/o2gxgz9r/9084/ – Pawan Jun 22 '17 at 10:37
  • You are using an array, rather you should use an object. Array of objects should be used if data for multiple users is coming. – Rahul Arora Jun 22 '17 at 10:40
0

use javascript's hasOwnProperty function,

if(json_object.hasOwnProperty('name')){
//do struff
}

Here

if (ajaxresponse.length > 0)
    {
        if(ajaxresponse.hasOwnProperty("Name"))
        {
            var Name = ajaxresponse[0].Name;
            var Age = ajaxresponse[1].Age;
            var Gender = ajaxresponse[2].Gender;
            var Country = ajaxresponse[3].Country;
            console.log(Name);
       }
    }
0

Make it a bit more general try something like this which will iterate through the user_details array setting properties for each item.

var ajaxresponse = response.user_details;
var user_details = ajaxresponse.reduce(function(details, detail){
    // details is the object we'll populate and will get assigned to user_details
    // detail is the current user detail object - Name/Age/Gender/Country

    // get property name for this "detail"
    var propertyName = Object.getOwnPropertyNames(detail)[0];

    // set the property and value for the current detail object
    details[propertyName] = detail[propertyName];

    // return the updated details object for the next iteration
    return details;
}, {});

console.log(user_details.Name);

This has the added bonus that any new properties in the result set will be handled automatically.

phuzi
  • 8,111
  • 3
  • 24
  • 43
0

the below code you can check the property present in JSON Array and also get the value of the property from Array

array.forEach(item=>{
          if(item.hasOwnProperty(propertyname)){
              if(item[propertyname]){
                resultArray.push(item[propertyname])
              }
           }
          
        })
Sumant Singh
  • 646
  • 1
  • 9
  • 12