See if value exists in deep nested json array

check if key value exists in json object javascript
javascript find value in nested object
check if key exists in json object javascript
get value from nested json object in javascript
javascript check if key exists in array of objects
check if value exists in json array angularjs
javascript get nested object property by string
hasownproperty

Here I have my simple json response:

Array
(
    [data] => Array
        (
            [id] => 3
            [type] => workspace
            [attributes] => Array
                (
                    [name] => testing
                    [slug] => testing
                    [data] =>
                    [created_at] => 
                    [updated_at] => 
                    [role] => Amazing
                    [last_accessed_at] =>
                )

        )

)

Is it possible to make a generic function that would simply look for the given value within the given path?.

For example I would like to make a function that would recursively search for a given value with a given key:

public function seeIfValueExistsInJson("data.attributes.slug", "testing"){

}

I would like to make it as generic as possible encase the first item of the response was not "data" and could be something else.

Has anyone seen/made anything similar and would be willing to share?

Thank you :)


Update: I have technically managed to do this. But I know this is not the best way possible as it just doesn't feel or look like it, and I would love to see your criticism on how it can be improved to help me improve my code even further:

public function extractData($fullPath, $value)
    {

        $jsonString = json_encode($this->json());
        $paths = explode(".", $fullPath);
        $oldPos = 0;
        $len = sizeof($paths) - 1;
        foreach ($paths as $path) {
            if (strpos($jsonString, $path) !== false) {
                $currPos = strpos($jsonString, $path);
                if ($currPos > $oldPos) {
                    if ($len === 0) {
                        $valuePos = strpos($jsonString, $value);
                        PHPUnit::assertTrue($currPos < $valuePos);
                        break;
                    }
                    $len--;
                }
                $oldPos = $currPos;
            } else {
                print("The path: '$path' is not within this Json response");
            }
        }
    }

As you can see this function turns the given response json into a string and gets the positions of each of the "path" indexs you give it (after exploding them) and then makes sure that the previous position of the index was smaller than the next (this way it means the next index path you are looking for has to be after) and then once it has reached the end of the loop it will (in my case using phpunit) assert that the value you have given is further along the list than the last index path. This does seem to have many flaws in terms of same string being in the response etc. So I would be welcoming to any feeback on how I could improve this


Since you already have an array, you can explode $fullPath and search each of the keys in that array. If there is no such key, return false. Else, check if the value of the path is equal with $value:

$arr = ['data' => ['id' => 3, 'type' => 'workspace',
        'attributes' => ['name'=>'testing', 'slug'=>'testing', 
                         'data' => '', 'created_at' =>'',
                         'updated_at' => '', 'role' => 'Amazing',
                         'last_accessed_at' => '']]];

function seeIfValueExistsInJson($arr, $fullPath, $value){
    $tempArr = $arr;
    $keys = explode('.', $fullPath);
    foreach($keys as $key){
      if(isset($tempArr[$key])){
          $tempArr = $tempArr[$key];
      }
      else return false;
    }
    return $tempArr === $value;
}

$result = seeIfValueExistsInJson($arr, "data.attributes.slug", "testing");
echo 'Result: ' . $result;

This will return:

Result: 1 

Safely Accessing Deeply Nested Values In JavaScript, Safely Accessing Deeply Nested Values In JavaScript Imagine we have a props objects, which might look something like the above example. the point, that we want to make sure a key or index exists before we try to access it. If you would rather pass in a string path instead of an array, the get function  Python Find if the nested key exists in JSON. Most of the time, JSON contains so many nested keys. Let’s see how to access nested key-value pairs from JSON directly. Let’s assume you have the following JSON data. and you want to check and access the value of nested key marks.


I strongly recommend against encoding the string as JSON and then searching the JSON. This strategy won't work in a generic sense. You need to traverse the data structure, probably using some kind of recursive function. (Which I won't attempt to write here.)

If the data comes in as JSON, you should first decode it into a data structure. (Treat the JSON string as a "black box.")

JavaScript, Given a JSON Object, the task is to check whether a key exists in Object or not using JavaScript. We're going to discuss Return value: It return a Example 2: This example checks for pro_1 of the obj by simple array access. filter_none. edit This is a short post intended to show the many different ways on how to safely access deeply nested values in JavaScript. The following examples all do the same thing and while they may vary in…


You can use array_walk_recursive PHP function.

<?php
$data = json_decode($json);
$hasData = false;
$searchString = "";
array_walk_recursive($data, function($value, $key) {
    $hasData = $hasData || $value == $searchString;
});

PS.: You may need to add a few tweaks for type checking. =D

PS. 2: I wasn't able to test this because I'm not on my PC atm.

How to check if a key exists in a JavaScript object, Imagine you have the following nested object and you want to retrieve the theme property. The simplest way is to check if the value equals to undefined Is it just me, or does JavaScript have objects but no classes? make sure that an object, function or array property exists before trying to use it so you don't get a ' can't  60 Fathoms Deep Equality. The difference between choosing eql and .ordered.members becomes more obvious when comparing arrays of objects. Mentioned before, eql is an equality assertion in Chai.js


nested-keys, Use property paths like 'a.b.c' to get a nested value from an object. Even works when keys Find if the provided key of an object exists and retrieve the value(s)   Print the json object nested in an array using Python I am working with a JSON file and am using Python. I am trying to print an object that is nested in an array. I would like to print select objects (e.g. "name", "thomas_id") from the following array (is it considered a 'list' of '


Test if a key exists anywhere in a nested object, Your code has a couple of problems: Semantic. You are using the construction key in obj , without checking if key is an actual property of obj . JavaScript | Check if a key exists inside a JSON object Given a JSON Object, the task is to check whether a key exists in Object or not using JavaScript. We’re going to discuss few methods.


jonschlinkert/get-value, has-any: Returns true if an object has any of the specified keys. | homepage · has -value: Returns true if a value exists, false if empty. Works with deeply nested  Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.