Issues with JSONPATH in typescript failing to grab any values

Searching for a specific config item validity using JSON path can be achieved by specifying the key name condition. This process works seamlessly on platforms like , accurately extracting the desired value:

https://i.sstatic.net/2ffAAnNM.png

In Typescript, the code implementation would look something like this:

import * as jsonpathPlus from 'jsonpath-plus';

const key = "configTwoEnabled"           
const configCurrentValue = jsonpathPlus.JSONPath({ path: `$.featureSwitches[?(@.key == "${key}")]`, json: jsonResponse })[0];

However, there might be instances where the JSON response may not return expected results. For example, querying with just $. retrieves all values but adding featureSwitches path could result in no output. Here's an illustrative snippet of the sample JSON structure:

{
    "featureSwitches": [
        {
            "key": "configOneEnabled",
            "isEnabled": true
        },
        {
            "key": "configTwoEnabled",
            "isEnabled": true
        },
        {
            "key": "configThreeEnabled",
            "isEnabled": true
        },
        {
            "key": "configFourEnabled",
            "isEnabled": false
        },
        {
            "key": "configFiveEnabled",
            "isEnabled": true
        }
    ]
}

Answer №1

It appears that your code is functioning properly when you replace the specified object with jsonResponse.

If $. does indeed return the entire list as mentioned, it is likely that the variable jsonResponse contains the following JSON object:

[
    {
        "key": "configOneEnabled",
        "isEnabled": true
    },
    {
        "key": "configTwoEnabled",
        "isEnabled": true
    },
    {
        "key": "configThreeEnabled",
        "isEnabled": true
    },
    {
        "key": "configFourEnabled",
        "isEnabled": false
    },
    {
        "key": "configFiveEnabled",
        "isEnabled": true
    }
]

You might want to consider adjusting your path to

$.[?(@.key == "${key}")]
(excluding the featureSwitches). However, it would be beneficial for us to see the actual structure of the jsonResponse object in order to provide more precise assistance.

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

Steps for transitioning from a mapped type to a discriminated union

Forgive me if this question has already been posed. I made an effort to search for a solution, but it seems I may not be using the correct terms. The issue arises with this particular structure. It involves a simple mapped type: type Mapped = { squ ...

Determining the height of dynamically rendered child elements in a React application

Looking for a way to dynamically adjust the heights of elements based on other element heights? Struggling with getting references to the "source" objects without ending up in an infinite loop? Here's what I've attempted so far. TimelineData cons ...

What is the reason for the retrieval of jquery-3.5.1.min.js through the request.params.id expression?

For my school project, I am using Express.js with TypeScript to create a simple app. This router is used for the edit page of a contact list we are developing. It displays the ID of the current contact being edited in the search bar. The problem arises whe ...

Which library do you typically employ for converting .mov files to mp4 format within a React application using Typescript?

As a web programming student, I have encountered a question during my project work. In our current project, users have the ability to upload images and videos. Interestingly, while videos can be uploaded successfully on Android devices, they seem to face ...

The type 'function that takes in a CustomEvent and returns void' cannot be assigned to a parameter of type 'EventListenerOrEventListenerObject'

When I upgraded from TypeScript version 2.5.3 to 2.6.1, my custom event setup started giving me an error. window.addEventListener('OnRewards', (e: CustomEvent) => { // my code here }) [ts] Argument of type '(e: CustomEvent) => ...

Swapping the content of the API response with Angular 11 in the HTML

When the output of row.remarks is 1, I want to display it as "passed" and when it's 0, I want it to be displayed as "fail" in the HTML while using mat-table. HTML <ng-container matColumnDef="remarks"> <th class="font& ...

What is the best way to send a string parameter from an Angular UI to a Node.js backend?

My goal is to transfer a string value from an Angular UI to a Node.js backend API, which will then search in MongoDB using the provided string value as shown below. I am attempting to receive input in enteredValue and pass it on to the http.get call as pa ...

Guide on creating a decorator for asynchronous functions that runs exclusively when using `Promise.resolve()`?

This decorator is specifically designed for analytics that triggers an event when a Promise is successfully resolved. class Foo { @LogEvent("success") async bar() { await someAction(); } } After researching online, it seems like I need to a ...

The absence of the 'classes' property in the MUI component type is causing an issue in Typescript Material UI

Simply put, typescript is giving me a hard time by complaining about the missing property classes on every material-ui component. Essentially, Typescript requires the presence of the classes property in nearly all material-ui components. Here is the error ...

Create a custom data type that consists of a specific set of keys from an object

Is there a way to create a type in TypeScript that includes only a subset of keys from an object? Consider the example object below: const something = { cannary: "yellow", coyote: "brown", fox: "red", roses: "white", tulipan: "purple", palmera: ...

limit the data types of values within an object using Typescript

When working with typescript, how can I define the type signature for a plain old javascript object that allows any key, but restricts the values to strings only? For example, {a:"foo"} and {b:"bar"} are considered valid values, while {a:[1,2,3]} and {b:3} ...

Angular 2 repeatedly pushes elements into an array during ngDoCheck

I need assistance with updating my 'filelistArray' array. It is currently being populated with duplicate items whenever content is available in the 'this.uploadCopy.queue' array, which happens multiple times. However, I want to update ...

Struggling with TypeScript compilation in a Vue.js project? Encounter error code TS2352

Here is my code snippet from window.ts import Vue from 'vue' interface BrowserWindow extends Window { app: Vue } const browserWindow = window as BrowserWindow export default browserWindow Encountering a compilation error Error message: TS2 ...

In order to effectively manage the output of these loaders, it may be necessary to incorporate an extra loader. This can be achieved by using the

I'm currently working with react typescript and trying to implement a time zone picker using a select component. I attempted to utilize the npm package react-timezone-select, but encountered some console errors: index.js:1 ./node_modules/react-timezo ...

Navigating through a dictionary in React TypescriptWould you like to learn

Currently, I am delving into the world of React and TypeScript. Within my journey, I have stumbled upon a dictionary representing various departments, with employee data stored in arrays. type Department = { Emp_Id: number, Name: string, Age: n ...

Confirm the object received from the API and assign default values

Seeking to extract data from an API and verify if all fields are strings, but if they are missing I aim to assign default values. My intention was to utilize the yup library to validate the object accordingly, ensuring that the returned function is prope ...

Structuring a TypeScript microservices repository on GitHub: Best practices to follow

Currently, I am in the process of designing a set of microservices. The structure I have been following involves each item having its own repository. my-project-logger my-project-numbers-service includes: my-project-logger type definitions + class obje ...

Creating a Circle with Pixi.js v4 and Typerscript in IONIC 2

I have been attempting to create a custom class in TypeScript that utilizes PIXI.js to draw circles. Below is the code for my home.ts class: import { Component, ViewChild, ElementRef } from '@angular/core'; import { NavController } from 'i ...

A step-by-step guide on leveraging swagger-autogen in TypeScript applications

Is it possible to integrate the swagger-autogen module into a Typescript project? I have attempted multiple methods, but have been unsuccessful. The error message "Failed" keeps appearing when using a swagger.js file: const swaggerAutogen = require("swagge ...

Start Transloco in Angular before the application begins

For our Angular project, we have implemented Transloco to handle translations. Within my typescript code, I am using the transloco service in this manner: this.translocoService.translate('foo.bar') I understand that it is crucial to ensure that ...