Search code examples
javajsonrest-assuredjsonpath

JSON get string with values only


Given json like this:

    {
       "key1":value1,
       "key2":value2
    }

Using rest-assured JsonPath

new JsonPath(json).getString("path")

it returns something like [key1=value1, key2=value2] Is there a way to return only values like [value1, value2] ?


Solution

  • Your question topic is unrelated to your question. But, you can use simple function to achieve your goal.

    function getValuesOnly(obj) {
     let values = []
    
     for(key in obj) {
       values.push(obj[key])
     }
    
     return values
    }
    

    above function will return the all the values within every key.Also you can use bellow function to get values even from nested objects.

    function getValuesOnlyNested(obj) {
      let values = [];
      for (key in obj) {
        if (typeof obj[key] !== "object") {
          values.push(obj[key]);
        } else {
          values = values.concat(getValuesOnlyNested(obj[key]));
        }
      }
      return values;
    }