Discovering ways to verify if an array is empty within JSON data using JMESPath?

I am presenting JSON data that looks like this:

[
  {
    "id": "i_1",
    "name": "abc",
    "address": [
      {
        "city": [
          "city1",
          "city2"
        ]
      },
      {
        "city": [
          "city1",
          "city2"
        ]
      }
    ]
  },
  {
    "id": "i_2",
    "name": "def",
    "address": [
      {
        "city": []
      },
      {
        "city": []
      }
    ]
  }
]

My objective is to extract only the data where the city array is not empty. Based on the above example, the output should be the first element with an id of i_1.

Can you explain how the json can be filtered using the JMESPath library?

Answer №1

Here is an example of how you can achieve this:

var array = [
  {
    "id": "i_1",
    "name": "abc",
    "address": [
      {
        "city": [
          "city1",
          "city2"
        ]
      },
      {
        "city": [
          "city1",
          "city2"
        ]
      }
    ]
  },
  {
    "id": "i_2",
    "name": "def",
    "address": [
      {
        "city": []
      },
      {
        "city": []
      }
    ]
  }
];

console.log(jmespath.search(array,"[?not_null(address[].city[])]"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jmespath/0.15.0/jmespath.js"></script>

Answer №2

If you want to achieve this using pure JavaScript, you can utilize the filter and every methods.

const items=[{"id":"i_1","name":"abc","address":[{"city":["city1","city2"]},{"city":["city1","city2"]}]},{"id":"i_2","name":"def","address":[{"city":[]},{"city":[]}]}]

const filtered = items.filter(i => i.address.every(a => a.city && a.city.length > 0))

console.log(filtered)

This code snippet will only return objects where every item in the address array contains a non-empty city array.

Answer №3

To achieve the same result without relying on the jmespath library, you can utilize the filter and `every methods from vanilla JS, which tends to be more efficient.

let jsonData = '{"data":[{"id":"i_1","name":"abc","address":[{"city":["city1","city2"]},{"city":["city1","city2"]}]},{"id":"i_2","name":"def","address":[{"city":[]},{"city":[]}]}]}'

let parsedData = JSON.parse(jsonData);
let dataItems = parsedData.data;
const filteredResult = dataItems.filter(item => item.address.every(addr => addr.city && addr.city.length))
console.log('id: ', filteredResult[0].id);
//jmespath alternative
console.log(jmespath.search({data: dataItems}, "data[*].address[*].city"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jmespath/0.15.0/jmespath.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Direct the /username path to /[user]/[tab].js instead of [user]/index.js in Next.js

My goal is to develop a user profile page that displays content based on the current tab the user is viewing. The tab is determined by what is provided in the URL (e.g. /username/tab1). The challenge I am facing is that one of the tabs the user can access ...

Information is only displayed within the Node Request function and is not accessible to

I am currently developing a small web scraping tool using Node (Express) to search URLs from a list. However, I'm encountering an issue with accessing the results of the search outside of the request callback function in a forEach loop. Can anyone hel ...

Matching Tables with JavaScript and JSON

After hours of coding, I'm stuck on a simple task and could really use some assistance. The "users" object contains user account information, with the function "get" meant to retrieve matching objects from this array. var users = [ { name ...

Is there a method in Angular to refresh or recompile a specific section or entire page that utilizes one-time bindings?

With numerous lists on our page containing potentially hundreds of items, we prioritize performance by implementing one-time bindings to update only when necessary and minimize the number of watchers. If we decide to utilize one-time bindings, is there a ...

Incorporating PHP generated content into Dart without using Ajax

My current website is built using PHP (Laravel) on the server side and Javascript on the client side. Now, I am interested in replacing the Javascript with Dart. Currently, I inject data into the Javascript on the webpage like this: <script> va ...

The process of obtaining HTML input using JavaScript

I have included the following code snippet in my HTML form: <input type="text" name="cars[]" required>' It is worth noting that I am utilizing "cars[]" as the name attribute. This allows me to incorporate multiple ...

Utilizing Jquery to interchange two values and update styling

I am looking to create a script that allows me to select a black div by clicking on it (turning it red), and then transfer the value from the black div into a white div with another click. The functionality works as expected when swapping values between tw ...

Accessing a child component's method within a parent component by making a call to it

I am facing an issue where I need to invoke a method in a child component from its parent component. Here is the specific scenario: Parent Component Example // ParentComponent.js class ParentComponent extends Component { render() { ret ...

Using jQuery to toggle the visibility of HTML elements

Hi there, I am trying to create an interactive HTML sidebar where each section shows its respective posts when clicked. However, I am facing issues as the content keeps hiding continuously. <div class="col-md-3"> <div class="list-grou ...

How to decode and access a nested JSON array in Swift: A guide

I'm struggling with parsing 10 arrays within an array from JSON to Swift and accessing the data. While I can successfully fetch the data via a REST API and print it out on the console, I am unsure of how to save it for further processing. JSON array ...

What is the most efficient method to import multiple MaterialUI components using a shared namespace without requiring the entire library to be imported

In order to prevent name mixing with other libraries, I want my MaterialUI components to be under the same namespace. For example, ensuring that <Box> references <MaterialUI.Box> and not <SomeOtherLibrary.Box>. Although it seems like a si ...

What is the best way to send an HttpPost request to a RESTful web service in order to transmit a URL with parameters that contains an array of values?

I am attempting to call a RESTful webservice in order to retrieve a JSON object. Initially, I made the call using HttpGet and it was successful. The URL structure required for this call looked something like: http://example.com//def.xxx?Name=save&Code= ...

Converting Object to XML without the need for [xmlns=""]

There is a Manual for Jackson XML write Object which is structured as follows: <Simple> <x>1</x> <y>2</y> </Simple> You can find more information about this in https://github.com/FasterXML/jackson-dataformat-xml. H ...

Can you explain the meaning of the code provided below?

I'm having trouble understanding the functionality of this code snippet: .bind(this); (I copied it from the Zurb Foundation dropdown plugin) .on('mouseleave.fndtn.dropdown', '[data-dropdown], [data-dropdown-content]', function ( ...

Encountered a TypeError in React 16.7: The function (0, _react.useState) is not recognized

Error: TypeError: (0 , _react.useState) is not a function React versions currently being used: "react": "^16.7", "react-dom": "^16.7", File src/App.js: import {memo, useState} from 'react' export default memo(() => { useS ...

When using async functions in iterative processes

In my current setup, I am utilizing a for-each loop to handle a list and specifically require element n to be processed only after element n-1 has completed: let elements = ["item1", "item2", "item3"]; elements.forEach(function(element){ someAsyncFun ...

Sort an array by mapping it in decreasing order based on the total sum of its elements

I came across a JSON structure that looks like the following: { "user": [ {"username": "x1", "pfp": "", "scores": [{"easy": 10, "normal": 1, "hard": 2, "oni&q ...

Decoding JSON data into Enum fields

Within my Android application, I encounter a straightforward JSON object containing basic key-value pairs. For example: {"username" : "billySmith", "gender" : 1} In addition, there is an enum with matching field names username and gender (String and int, ...

Abort S3 file upload using ASW-SDK

Is there a way to abort an upload without raising an error Upload aborted. when calling upload.abort()? import { PutObjectCommandInput, S3Client } from '@aws-sdk/client-s3'; import { Progress, Upload } from "@aws-sdk/lib-storage"; cons ...

Modify the color scheme of the Highcharts Maps to display a range of colors according to the minimum and maximum values

I'm currently working on a Vue project where I need to display data on a world map. However, I'm facing an issue with changing the color on the map. I want to utilize the minColor and maxColor options in the colorAxis configuration, but for some ...