Search a JSON Array for an Object Containing a Value Matching a Pattern

Search an array for matching attribute

for(var i = 0; i < restaurants.length; i++)
{
if(restaurants[i].restaurant.food == 'chicken')
{
return restaurants[i].restaurant.name;
}
}

How to filter an array of objects based on values in an inner array with jq?

Very close! In your select expression, you have to use a pipe (|) before contains.

This filter produces the expected output.

. - map(select(.Names[] | contains ("data"))) | .[] .Id

The jq Cookbook has an example of the syntax.

Filter objects based on the contents of a key


E.g., I only want objects whose genre key contains "house".

$ json='[{"genre":"deep house"}, {"genre": "progressive house"}, {"genre": "dubstep"}]'
$ echo "$json" | jq -c '.[] | select(.genre | contains("house"))'
{"genre":"deep house"}
{"genre":"progressive house"}

Colin D asks how to preserve the JSON structure of the array, so that the final output is a single JSON array rather than a stream of JSON objects.

The simplest way is to wrap the whole expression in an array constructor:

$ echo "$json" | jq -c '[ .[] | select( .genre | contains("house")) ]'
[{"genre":"deep house"},{"genre":"progressive house"}]

You can also use the map function:

$ echo "$json" | jq -c 'map(select(.genre | contains("house")))'
[{"genre":"deep house"},{"genre":"progressive house"}]

map unpacks the input array, applies the filter to every element, and creates a new array. In other words, map(f) is equivalent to [.[]|f].

Search JSON elements with in a JSONArray

You could try this:

    public String returnSearch(JSONArray array, String searchValue){
JSONArray filtedArray = new JSONArray();
for (int i = 0; i < array.length(); i++) {
JSONObject obj= null;
try {
obj = array.getJSONObject(i);
if(obj.getString("name").equals(searchValue))
{
filtedArray.put(obj);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
String result = filtedArray.toString();
return result;
}

Codes are self explanatory, so comments are omitted, hope it helpful.

Regular expression to extract a JSON array

If the number of items in the array is limited (and manageable), you could define it with a finite number of optional items. Like this one with a maximum of 5 items:

"category":\["([^"]*)"(?:,"([^"]*)"(?:,"([^"]*)"(?:,"([^"]*)"(?:,"([^"]*)")?)?)?)?

regex101 example here.

Regards.



Related Topics



Leave a reply



Submit