Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a particular JSON Object is available or not in php

Tags:

json

php

I have following JSON:

$p={
  "main1" : [
    {
      "child1" : valueA,
      "child2" : valueB,
      "child3" : valueC,
    },
    {
      "child1" : value1,
      "child3" : value3,
    },
  ],
  "main2" : "valueMain2"
}

The element child2 has to be checked if it exists or not and then the value is taken. I am using json_decode:

$response = json_decode($p,true);

How do I check if an element exists or not in PHP? Do I have to make separate function or is there built-in functionality?

like image 463
user2129794 Avatar asked Mar 16 '13 01:03

user2129794


People also ask

How check JSON is valid or not in PHP?

Simple function to validate JSON. If you have to validate your JSON in multiple places, you can always use the following function. function is_valid_json( $raw_json ){ return ( json_decode( $raw_json , true ) == NULL ) ? false : true ; // Yes!

How check JSON object is empty or not in PHP?

$x = (array)$obj; if (empty($x)) ... Or cast to an array and count() : if (count((array)$obj)) ...

How do I check if an object is JSON?

The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JSchema) method with the JSON Schema. To get validation error messages use the IsValid(JToken, JSchema, IList<String> ) or Validate(JToken, JSchema, SchemaValidationEventHandler) overloads.

Is JSON object in PHP?

PHP has some built-in functions to handle JSON. First, we will look at the following two functions: json_encode() json_decode()


2 Answers

The same way you'd check if a key of any array exists:

with isset($array['key']) or array_key_exists('key',$array).

like image 74
lafor Avatar answered Sep 28 '22 05:09

lafor


Here's how I've been doing it.

$child2exists = count($response['main1']['child2']);

If ($child2exists == 1) 
{ 
    echo "EXISTS"; 
}
else
{ 
    echo "DOESNT EXIST"; 
}

Hope this helps.

like image 36
Cully Avatar answered Sep 28 '22 05:09

Cully