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

I successfully merged two arrays (decks of cards) without using recursion, but I'm curious to understand where I went wrong with the recursive approach

Currently, I am working on a function that shuffles two arrays together using recursion. The goal is to combine the top and bottom halves of a deck of cards into a single array with elements interleaved. For example: The first element should come from the ...

worldpay implements the useTemplateForm callback function

My experience with implementing worldpay on my one-page Angular app (Angular 1.x) has been mostly positive. I have been using the useTemplateForm() method to generate a credit card form and retrieve a token successfully. However, I have encountered an issu ...

Issue with Django div reloading: Using ajax GET after POST does not fetch the most recent database model instances

Within a chat-like application, I am utilizing ajax calls to POST a new message and dynamically update the messages displayed on the page without having to reload the entire page. The ajax call for posting functions correctly as it creates a new message in ...

Error retrieving content from website: Failed to connect to http://roblox.plus:2052/limiteds

Whenever I try to execute the code below, an error message pops up: file_get_contents(): failed to open stream: Connection refused $file = file_get_contents('http://roblox.plus:2052/limiteds'); $decode = json_decode($file, false); foreach ...

Encountering difficulties with displaying error messages on the Material UI datepicker

I am currently utilizing React Material UI There is a need to display an error based on certain conditions that will be calculated on the backend. Although I have implemented Material UI date picker, I am facing issues with displaying errors. import * as ...

Callback function triggered upon the creation of a DOM node

I am in search of a way to have a specific callback function run each time a div that matches a particular selector is added to the DOM. I have explored the DOM events documentation and the event closest to what I need seems to be "load", however, it does ...

Error TS2307: Module 'calculator' could not be located

Running a Sharepoint Framework project in Visual Studio Code: This is the project structure: https://i.stack.imgur.com/GAlsX.png The files are organized as follows: ComplexCalculator.ts export class ComplexCalculator { public sqr(v1: number): number ...

transforming JSON data into an array format on the fly

When I make a call to an endpoint in my C# code, it returns data structured like this: { "name":"test", "clients": { "client1": {"id": "1", "count": "41"}, "client2": {"name": "testName"}, "client3 ...

issue with integrating promise in angular 4

I'm currently learning about promises and how to implement them in Angular. I have written the following code in StackBlitz. My goal is to display the array whenever it contains a value by using promises in Angular. This is my HTML code: <h2>A ...

Uncover the valuable information within a string using regex in JavaScript

I am looking for a solution to extract key values from a string that looks like this: <!-- Name:Peter Smith --><!-- Age:23 --> My goal is to create a standard function that can extract any value needed. The function call would be something like: var ...

Transform the size and convert an object from a picture into text based on the user's scrolling

I've been intrigued by the scrolling effects used on websites like Google SketchUp and Google Plus. It's fascinating how elements can transform as you scroll down the page. For example, on Google SketchUp's site, the banner starts off integr ...

Developing tests for an asynchronous function

I recently encountered a bug in my AWS Lambda code written in NodeJS 6.10 that caused me two sleepless nights. I didn't conduct integration testing, relying solely on unit tests, which led to the oversight. After inserting return workerCallback(err);, ...

How come jQuery is retaining the original DOM element classes even after I have modified them using jQuery?

Here is the code snippet I am working on: $(".drop-down-arrow-open i").click(function(){ console.log("The click function for .drop-down-arrow-open is triggered even when it is closed"); let thisParent = $(this).closest(".projects-container").find(".need ...

Creating models or bulk creating promises in a seed file

When working with a promise chain to add data in JavaScript, I usually start by using Node.js or another method and it works fine (with some variations). However, when attempting to implement this promise chain in a sequelize seed file with the sequelize- ...

In my Express Javascript application, I recently encountered a challenge where I needed to export a const outside of another

I am currently working with a file named signupResponse.js const foundRegisterUser = function(err, foundUser){ if(!err){ console.log("No errors encountered") if(!foundUser){ if(req.body.password == req.body. ...

After signing out, the function getRedirectResult in Firebase is being invoked

I'm a bit confused about some interesting behavior I've noticed while working with Firebase. Although I never used the older version, I believe getRedirectResult is a newer feature since they partnered with Google. Currently, I am using Vue.js a ...

The Dropdownlist jQuery is having trouble retrieving the database value

Within my database, there is a column labeled Sequence that contains integer values. For the edit function in my application, I need to display this selected number within a jQuery dropdown list. When making an AJAX call, I provide the ProductId parameter ...

Display PDF blob in browser using an aesthetically pleasing URL in JavaScript

Using Node, I am retrieving a PDF from the server and sending it to my React frontend. My goal is to display the PDF in the browser within a new tab. The functionality works well, but the URL of the new tab containing the PDF is not ideal. Currently, the U ...

What methods does Enzyme have for determining the visibility of components?

I am facing an issue with a Checkbox component in my project. I have implemented a simple functionality to hide the checkbox by setting its opacity : 0 based on certain conditions within the containing component (MyCheckbox) MyCheckBox.js import React fr ...

Tips for wrapping a function call that may occasionally involve asynchronous behavior to ensure it runs synchronously

I am dealing with a function that functions as follows: _setDataChunk: function (action) { var self = this; /* some code */ var data = self._getDataChunk(action); populateWidget(data); } Sometimes GetDataChunk cont ...