Ways to confirm the presence of specific keys in a JSON:

After successfully converting an excel sheet's content into a JSON format, my next task is to perform some validation on it.

The requirement is to ensure that the jsonData variable contains specific keys in a particular order: Breakfast, Lunch, Snack, and Dinner.

To start with the assertion process, I attempted the following test:

const jsonData = [{  
  "Breakfast": "Cereal",
  "Lunch": "Chicken",
  "Snack": "Biscuit",
  "Dinner": "Pork",
  "Drinks": "Water"
}]

expect(jsonData).to.be.an('array').that.contains.keys('Breakfast')

Unfortunately, running this code resulted in an error:

Answer №1

It seems that the to.contain.keys method can only be applied to the first object in an array, not the entire array itself.

You may want to try extracting that first item and then applying the assertion.

const jsonData = [{  
  "Breakfast": "Cereal",
  "Lunch": "Chicken",
  "Snack": "Biscuit",
  "Dinner": "Pork",
  "Drinks": "Water"
}]

expect(jsonData).to.be.an('array')

const firstItem = jsonData[0]
expect(firstItem).to.contain.keys('Breakfast')

Alternative syntax for chai keys assertion

After reviewing the documentation, it appears that the correct syntax for checking keys might be using .include.any.keys.

You could try doing:

expect(firstItem).to.include.any.keys('Breakfast')

Simpler approach

If you simply need to check if "Breakfast" exists, you can compare it to undefined:

For the first object:

expect(jsonData[0].Breakfast).to.not.eq(undefined)

For every object in the array:

jsonData.forEach(item => {
  expect(item.Breakfast).to.not.eq(undefined)
}

Answer №2

Thank you all for your valuable contributions. After some consideration, I have finalized the following code snippet. Feel free to share any suggestions for improvement or alternative approaches.

// Referencing data from testdata.json
const columns = testdata.Meals.columns

const keys = Object.keys(data[0])
const values = Object.values(data[0])

const data = [{
  "Breakfast": "Toast",
  "Lunch": "Salad",
  "Snack": "Fruit",
  "Dinner": "Steak",
  "Drinks": "Juice"
}]

cy.get(columns).each(($element, index, $list) => {
  expect(data[0]).to.haveOwnProperty(keys[index])

  // Check the order of key-value pairs
  if (index == 0) {
    expect(keys[i]).to.equal(columns[index])
    expect(values[index]).to.equal(context.breakfastName)
  } else if (index == 2) {
    expect(keys[index]).to.equal(columns[index])
    expect(values[index]).to.equal(context.snackName)
  } else if (index == 4) {
    expect(keys[index]).to.equal(columns[index])
    expect(values[index]).to.equal(context.drinkName)
  }
})

The contents of testdata.js:

{
 "Meals": {
  "columns": [
    "Breakfast",
    "Lunch",
    "Snack",
    "Dinner",
    "Drinks"
  ]
 }
}

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

Unpacking a container containing interconnected objects

Creating a command line two-player chess game has been an exciting challenge for me. I've structured it with a class for each type of chess piece and a main board class, which is outlined below: class Board attr_accessor :board, :choice def init ...

Displaying the format when entering a value with react-number-format

How to Display Format Only After Full Value Inserted in react-number-format I recently implemented the react-number-format package for formatting phone numbers. import { PatternFormat } from 'react-number-format'; <PatternFormat value={v ...

Do I need to utilize getStaticProps along with JSON imports in Next.js?

Is it necessary to use getStaticProps in order to render static data from a JSON or typescript file, or can the data be imported without using getStaticProps? The documentation I read didn't provide a clear answer. projects.tsx const projects: [ { ...

Is there a Problem with Paging in Meteor with Jquery?

I implemented Pagination using Jquery, but I encountered an issue along with the following error message: Uncaught TypeError: Object [object Object] has no method 'customPaginate' I am unsure how to resolve this problem. Could you please take ...

Causing a click event to occur results in crashing the browser

Take a look at this link: example on jsfiddle Why does the click event keep triggering multiple times when a div is clicked, eventually causing the browser to crash? What could be causing this issue and how can it be resolved? The actual div contains a l ...

show a fresh new page using react router

I have recently developed a mobile app that showcases a collection of movies. Currently, it is static and I am looking to implement a react router for navigation. Specifically, I want the user to be directed to a detail page for a TV Show when they click o ...

Having trouble constructing json.me using the provided source code

Looking to incorporate JSON into my Java ME project, I've come across a couple promising tutorials. However, I'm struggling to locate the necessary jar file. Here are two links I found containing the source code: https://github.com/upictec/org ...

Guide on saving a json file with a dictionary inside a list into a CSV file using Python

Below is the JSON data that I have: "item": [ { "id": "3", "num": 0, "name": "de", "leve": { "label": [ "Ini", ...

The JSON output is only displaying the final object in the array

Currently, I am working on creating a custom JSON feed for my WordPress page. The issue I am facing is that the loop seems to be overwriting every object, resulting in only the last object being printed as JSON. I have attempted moving the echo inside the ...

What is the best way to arrange a collection of JObjects in VB.net?

Currently, I am working with VB.net (4.5) and utilizing the Newtonsoft Json Linq package. Within my code, there is an array named BuyList that consists of 100 market orders structured as follows: {{ "Quantity": 0.14333804, "Rate": 6693.01 }} My obje ...

AngularJS form submission with Ajax requiring a double click to successfully submit the form

I need to perform the following activities on my HTML page: User inputs email and password for registration Form is sent to Controller when user clicks Submit Controller uses AJAX to create JSON request to RESTful Server and receives response from server ...

Could someone share an instance of an AngularJS configuration that continuously checks for new data and automatically refreshes the user interface once the data is obtained?

Struggling to find a suitable example for this scenario. I am looking to create a chart directive that will be updated every minute by fetching data from a web service. Currently, I have a service that acts as a wrapper for the web service. My controller ...

Tips for creating a plug-in plugin and applying the necessary parameters

(function( $ ){ var functions = { init : function( options ) { var settings = $.extend({ //Declaring default settings that can be overridden in the plugin call code: 7, listHe ...

JQuery is having trouble locating a variable in a different JavaScript file

Currently, I am utilizing the cakephp framework and have developed 2 distinct javascript files which I have stored in my webroot/js directory. The first javascript file includes modal dialog variables that define the settings for the dialog boxes. The seco ...

What is the process of sending a post request using axios to insert data into a database in React

I am currently working on a login system using mysql, axios, express, and react. The database connections are functioning properly, but I am encountering errors specifically with these two posts, displaying messages like "ERR_CONNECTION_REFUSED" and UNCAUG ...

Encountering a bizarre npm issue while attempting to execute npm install for brain.js

Encountering a puzzling error while attempting to install brain.js. Unsure of why Python is being mentioned during the installation process via npm, as there are no similar situations found on Google (and I'm not quite sure how to search for it). G:& ...

Offline parsing of JSON data on Android

Hello everyone, I'm a newbie in the exciting world of Android and I've encountered a problem. I am currently working on an Android project that requires a JSON parser. The challenge lies in obtaining my JSON file from a web service created using ...

Struggling to master YAML integration with Google App Engine?

Seeking assistance with YAML as I am new to it: application: baking-tutorial version: secureable runtime: python27 api_version: 1 threadsafe: true handlers: - url: /robots\.txt static_files: static/robots.txt upload: static/robots\.txt - url: ...

Displaying Font Awesome icon within a loop in a Vue.js component

I am trying to display icons within a v-for loop. The data for the links and icons is stored in a JSON file. However, I am facing an issue when trying to use Font Awesome icons with Vue.js. When I include Font Awesome via CDN, everything works fine. But wh ...

Implementing a delete functionality within a loop on a JavaScript object array

I have a JavaScript object with the following structure: var partner = { p_name: { value: partner_name, label: "Name" }, p_id: { value: partner_ID, label: "ID" }, p_status: { value: partner_status, label: "Status" }, p_email: { value: partner_emai ...