How to check if a json key exists?

后端 未结 13 2076
一整个雨季
一整个雨季 2020-11-27 11:38

So, I get some JSON values from the server but I don\'t know if there will be a particular field or not.

So like:

{ \"regatta_name\":\"ProbaRegatta\"         


        
相关标签:
13条回答
  • 2020-11-27 12:07

    just before read key check it like before read

    JSONObject json_obj=new JSONObject(yourjsonstr);
    if(!json_obj.isNull("club"))
    {
      //it's contain value to be read operation
    }
    else
    {
      //it's not contain key club or isnull so do this operation here
    }
    

    isNull function definition

    Returns true if this object has no mapping for name or
    if it has a mapping whose value is NULL. 
    

    official documentation below link for isNull function

    http://developer.android.com/reference/org/json/JSONObject.html#isNull(java.lang.String)

    0 讨论(0)
  • 2020-11-27 12:08
    I used hasOwnProperty('club')
    
    var myobj = { "regatta_name":"ProbaRegatta",
        "country":"Congo",
        "status":"invited"
     };
    
     if ( myobj.hasOwnProperty("club"))
         // do something with club (will be false with above data)
         var data = myobj.club;
     if ( myobj.hasOwnProperty("status"))
         // do something with the status field. (will be true with above ..)
         var data = myobj.status;
    

    works in all current browsers.

    0 讨论(0)
  • 2020-11-27 12:13

    You can check this way where 'HAS' - Returns true if this object has a mapping for name. The mapping may be NULL.

    if (json.has("status")) {
       String status = json.getString("status"));
    }
    
    if (json.has("club")) {
       String club = json.getString("club"));
    }
    

    You can also check using 'isNull' - Returns true if this object has no mapping for name or if it has a mapping whose value is NULL.

    if (!json.isNull("club"))
        String club = json.getString("club"));
    
    0 讨论(0)
  • 2020-11-27 12:15

    You can use the JsonNode#hasNonNull(String fieldName), it mix the has method and the verification if it is a null value or not

    0 讨论(0)
  • 2020-11-27 12:16

    Try this:

    let json=yourJson
    
    if(json.hasOwnProperty(yourKey)){
        value=json[yourKey]
    }
    
    0 讨论(0)
  • 2020-11-27 12:18

    Try this

    if(!jsonObj.isNull("club")){
        jsonObj.getString("club");
    }
    
    0 讨论(0)
提交回复
热议问题