Exploring JSONPath in Cypress

I am currently working on extracting a JSON path for the specific HTML content with the language code DE

Below is an example of the JSON data:

{
"name": "Name",
"text": "",
"html": "HTML content",
"tags": [],
"translations": [
    {
        "html": "Irrelevant HTML content",
        "text": "",
        "language": {
            "code": "AF",
            "name": "AF"
        }
    },
    {
        "html": "Desired HTML content",
        "text": "",
        "language": {
            "code": "DE",
            "name": "German"
        }
    }
],

}

So far, I have only managed to access the first translation using

const afLang = requestPromptsJsonRequest.translations[0].html;
in Cypress. I am still figuring out how to filter by language code rather than just the index number in the translations array.

Answer №1

Cypress includes a customized version of lodash with a find method that supports pattern matching.

Example test:

const jsonData = {
  ...  // data as described in the question
};

const translation = Cypress._.find(jsonData.translations, {language: { code: 'DE'}})
const html = translation.html
expect(html).to.eq('HTML I want')      // assertion passes

Runnable demonstration:

const jsonData = {
  "name": "Name",
  "text": "",
  "html": "HTML content",
  "tags": [],
  "translations": [
    {
      "html": "HTML I don't want",
      "text": "",
      "language": {
        "code": "AF",
        "name": "AF"
      }
    },
    {
      "html": "HTML I want",
      "text": "",
      "language": {
        "code": "DE",
        "name": "German"
      }
    }
  ]
}

const translation = _.find(jsonData.translations, {language: { code: 'DE'}})
document.querySelector('span').innerText = translation.html
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
<span id="result"></span>

Answer №2

Below is the TypeScript code snippet for achieving the same functionality:

import * as jsonpath from 'jsonpath';

const jsonData = {
  "name": "Name",
  "text": "",
  "html": "HTML content",
  "tags": [],
  "translations": [
    {
      "html": "HTML I don't want",
      "text": "",
      "language": {
        "code": "AF",
        "name": "AF"
      }
    },
    {
      "html": "HTML I want",
      "text": "",
      "language": {
        "code": "DE",
        "name": "German"
      }
    }
  ]
};

const htmlWithLanguageCode = jsonpath.query(jsonData, '$.translations[?(@.language.code == "DE")].html');

console.log(htmlWithLanguageCode);

Answer №3

A useful alternative to using JSON Path is to utilize Array.find() in order to access the correct language code within the translations object.

const data = {
  name: 'Name',
  text: '',
  html: 'HTML content',
  tags: [],
  translations: [
    {
      html: "HTML I don't want",
      text: '',
      language: {
        code: 'AF',
        name: 'AF',
      },
    },
    {
      html: 'HTML I want',
      text: '',
      language: {
        code: 'DE',
        name: 'German',
      },
    },
  ],
};

// To retrieve the desired object, we can use `.find()` on the `translations` array.
const deHTML = data.translations.find((x) => x.language.code === 'DE').html;
console.log(deHTML)

Another option is to encapsulate this variable assignment into a function.

const data = {
  name: 'Name',
  text: '',
  html: 'HTML content',
  tags: [],
  translations: [
{
  html: "HTML I don't want",
  text: '',
  language: {
    code: 'AF',
    name: 'AF',
  },
},
{
  html: 'HTML I want',
  text: '',
  language: {
    code: 'DE',
    name: 'German',
  },
},
  ],
};

const getHTMLByLanguageCode = (code) => {
  return data.translations.find((x) => x.language.code === code).html
}

const afHTML = getHTMLByLanguageCode('AF');
console.log('afHTML is: ' + afHTML);
const deHTML = getHTMLByLanguageCode('DE');
console.log('deHTML is: ' + deHTML);

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

Encountering "Invalid hook call" error with React Router while integrating Higher Order Components for authentication

Dealing with an error: React Router shows "Invalid hook call" with higher-order components for authentication Dilemma I have developed two distinct approaches for authentication wrappers in my React components with React Router. The first method functions ...

DiscoverField Component with Button Functionality and Checkbox Dilemma

I'm working with Vue 3, Vuetify, and TypeScript for my searchField component. Inside, I have two buttons: FreeItemMaster and PatternMaster. Clicking on these buttons should change their background color and display respective content below them. Howev ...

How to effectively utilize TypeScript in a team environment using both Atom and VSCode?

Our team utilizes TypeScript with both Atom and VSCode as our editors, but we are facing challenges with the tsconfig.json file. VSCode is not recognizing the typings, causing the namespace for 'ng' (for Angular 1.x) to be unknown in VSCode. Wh ...

Difference between JSON field being set to null and the field not being present in the

Is there a way to distinguish between a JSON field being set to null versus the field not being present when unmarshalled into a struct using golang? Both scenarios result in the value in the struct being nil, but I need to determine if the field originall ...

Having trouble getting my Angular project up and running - facing issues with dependency tree resolution (ERESOLVE)

Currently, I am in the process of following an Angular tutorial and I wanted to run a project created by the instructor. To achieve this, I referred to the steps outlined in the 'how-to-use' file: How to use Begin by running "npm install" within ...

Using "jq" to properly format multi-line text for escaping purposes

Let's say I have a multi-line text that needs to be escaped: printf "\"aaa\"\nbbb" "aaa" bbb I'm attempting to escape it using the command jq -aR: printf "\"aaa\"\nbbb"| jq -aR "\"aaa\"" "bbb" ...

Getting JSON data from HttpResponse returned by a Django view

I have encountered a situation in one of my Django apps where the method in a view is returning a HttpResponse object. json_str = json.dumps(json_dict) return HttpResponse(json_str, content_type="application/json") While writing tests for this app in the ...

The search is on for the elusive object that Angular 2/4

Why am I encountering the error message saying "Cannot find name 'object'"? The error message is: Error: core.service.ts (19,23): Cannot find name 'object'. This error occurs in the following line of code: userChange: Subject<ob ...

Create type declarations using the Typescript compiler by running the command:

After generating my definition file ".d.ts" using tsc --declaration or setting declaration as true in the tsconfig.json, I noticed that the generated files are missing declare module "mymodule" {... } This appears to be causing issues with "tslint" which ...

Issues with PHP server handling JSON files

I'm having some trouble retrieving server data to display in a table on my iPhone. The process involves the standard flow of server - php_interface - iOS. Initially, I attempted to use an echo json_encode(array) setup, but ran into issues with populat ...

Serializing data in OData protocol

Struggling for the past 2 months to devise a unique solution for custom serializing an entity returned from an OData controller. Desperately seeking assistance! The scenario is fairly straightforward, and I have distilled it even further to pinpoint the i ...

Converting a sophisticated PHP object into a JSON string

I'm struggling with parsing a complex object in PHP to create a Json String. Despite searching through various examples online, none of them seem to work for me. To add to the challenge, my hosting platform only supports PHP 5.2 and I cannot upgrade i ...

Utilizing ExpressJS for IP handling combined with AngularJS for $http GET requests

Struggling to grasp ExpressJS, I'm facing difficulties in displaying the IP address from an Express route in the browser using an Angular controller. To achieve this, I am utilizing two Node.js modules - request-ip and geoip2. These modules help me r ...

Standardize the JSON response

Looking for some assistance with the code snippet below: import requests import json import pandas as pd url = "https://www.pedrofonseca.eu/trabalho/projectoslei/api/projects/getByLegislature/XIV" response = requests.get(url) json_response = re ...

Using JSON strings and the .format() method in Python3

My goal is to create a JSON string using the .format() method. However, when I attempted to do so with the code below: TODO_JSON = '{"id": {0},"title": {1},"completed:" {2}}' print(TODO_JSON.format(42, 'Some Task', False)) I encounter ...

Could JSON be the solution for combining a number and a string in a single key-value pair?

I am working on defining a nested JSON object that will store a key value pair with an integer (representing the amount of something) in use case 1, and a key value pair with a string (UUID) in use case 2. The ultimate goal is to analyze this data in futu ...

Utilizing ASP.net's (VB code behind) functionality to efficiently parse JSON data retrieved from Facebook's

Seeking to experiment with ASP.net rather than my usual classic ASP, I am looking for examples on parsing out the name and id from a Facebook API Graph call JSON response. The JSON data retrieved from Facebook appears as follows: { "data": [ { ...

Is there a way to replace null values with empty strings when using json_encode?

I'm struggling to change null values to empty strings in the output of my json_encode: if ($uresult->num_rows >0) { while($urow = $uresult->fetch_assoc()) { $rresult = mysqli_query($con,"SELECT * FROM allid WHERE postid='$oldi ...

challenges with template inheritance: when one template takes precedence over another

I have encountered an issue with my two HTML templates, login.html and signup.html. Both of these files inherit from the base.html file, but there seems to be a problem where one file is overriding the title and content of the other. So when I visit /login ...

Next.js encountered an error when trying to locate the 'net' module while working with PostgreSQL

I'm facing a challenge in my Next.js project while attempting to retrieve all records from a table. The error message I'm encountering is "Module not found: Can't resolve 'net'" with an import trace pointing to multiple files withi ...