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: https://i.sstatic.net/3XJuF.png

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

Every time Jquery tries to retrieve cookies, it consistently returns as undefined

Having trouble accessing Application cookies using jquery in my Asp.Net MVC App. Check out this Screenshot of Cookie and its Value. I've been trying to access the Cookie with $.cookie('ASP.NET_SessionId'); but it keeps returning "undefined" ...

Inconsistencies in spacing between shapes bordering an SVG Circle using D3.js are not consistent across platforms

After creating a SVG circle and surrounding it with rectangles, I am now attempting to draw a group of 2 rectangles. The alignment of the rectangle combo can either be center-facing or outside-facing, depending on the height of the rectangle. However, I am ...

Creating custom mesh Morph Target Animations using THREE.js

I'm currently working on creating an animation that showcases the revolution of a 2D function around an axis to produce a 3D surface. Successfully rendering the surface, my next task is to implement the animation section using MorphTargets. Despite m ...

The API is providing data, but it's being returned within an ambiguous object. What could be causing this confusion?

Utilizing https and async for simultaneous calls to retrieve two objects, then storing them in an array. The call is structured as follows: if (req.user.isPremium == false) { // Free user - Single report let website = req.body.website0; let builtWit ...

What is the process for converting a CSV file to JSON format using node.js?

I am working on converting a CSV file from Clash Royale into an array. The CSV file has over 40 properties in its header or data. For example: name level count upgrade cost common 14 5, 20, 50, 100 rare 12 50, 150, 400, 1000 Below is my node.j ...

When utilizing an object within another object for a select option in Vue.js, the value may not update as expected

I'm currently working with an array of posts that includes a user for each post. I have a select field where I can change the user associated with a post. However, only the user's id updates on the page and not their username. Is there a way to e ...

Title: "Customizing Labels on Stack Bars and Lines in D3.js Visualization"

Currently working on a stacked bar chart with a line chart on dual axis using D3.js and facing difficulty aligning labels correctly. Check out the code I have experimented with so far: https://plnkr.co/edit/doobXBC5hgzvGwDLvArF?p=preview I am looking to ...

Stopping the interval in Vue before the component is destroyed

I am currently facing an issue with a countdown timer implemented on a component. The timer functions properly, however, I want it to stop counting down once the user navigates away from the page where the component is located. I have attempted to use cl ...

Steps to handle the change event of a p:inputText element

In my current setup, I am utilizing p:inputText and have the need to trigger a javascript function that will update the searchField in the backend bean. <p:inputText required="true" placeholder="#{cc.attrs.searchTip}" value="#{cc.attrs.queryProperty}" ...

Retrieving data from a JSON file with fields scattered throughout multiple dictionaries

While working on extracting data from a nested JSON file in Python 3.8, I encountered a KeyError related to the 'extended_tweet' key: extended_tweet = data[str(i)]['extended_tweet']['full_text'] KeyError: 'extended_tweet ...

JavaScript button click changes the selected row's color in a DataTable

I am looking to dynamically change the color of a row in my Datatable when a specific button is clicked. Here is the HTML code snippet for the rows: <tr role="row" class="odd"></tr> <tr role="row" class="even selected"></tr> & ...

What is the most efficient way to transfer a value from the main application file to a router file using the express framework

Currently, I am developing an Express application with multiple routes. To ensure modularity, each route will have its own file stored in a dedicated routes folder. One challenge I encountered is sharing a common value across all routes. Specifically, I n ...

The data type for JSON writing is not valid (NSConcreteMutableData)

My attempt to send a JSON request using AFNetworking is resulting in an error indicating that the JSON text did not start with array or object and option to allow fragments not set: NSString *post = [[NSString alloc] initWithFormat: @"{& ...

I'm facing an issue where I am only able to update the first record in the database using axios and Post

There seems to be a strange issue where only the first record in the database can be updated, even though all records can be retrieved without any problems. Here is the situation: https://i.sstatic.net/bK5aI.png To clarify further: Since names are unique, ...

How to drag an item onto another element using Vue.Draggable without the need for adding or removing

Are you familiar with the library https://github.com/SortableJS/Vue.Draggable? I am trying to achieve a drag and drop functionality where I can drag a file into a folder. However, I am facing an issue as the @change event only provides data about the drag ...

Issue with video.js text track memory leakage (WebVTT/VTT)

I am utilizing Video Text Tracks to showcase advanced live information on top of the video. A new video is loaded every few minutes, each with its own .webvtt file (consisting of 2-3k lines). Although everything is functioning properly, there is a persis ...

I am facing an issue in JavaScript where one of my two timers is malfunctioning

While working on my tank game, similar to Awesome Tanks, I encountered an issue with the AI tank shooting mechanic. I set up a separate timer for the AI tank to shoot a bullet, but when I attempt to run it, I receive an error stating that AItimer is not de ...

eliminate the gap in the MUI Accordion when it is expanded

How can I prevent the Accordion MUI component from moving and applying top and bottom margins to summary elements in expanded mode? I added the following code to the summary element but it doesn't seem to be working. Any suggestions on how to fix this ...

I'm trying to create a horizontal list using ng-repeat but something isn't quite right. Can anyone help me figure out

Feeling a bit lost after staring at this code for what seems like an eternity. I'm trying to create a horizontal list of 2 image thumbnails within a modal using Angular's ng-repeat. Here's the HTML snippet: <div class="modal-body"> ...

Express Concurrency: Managing Multiple Tasks Simultaneously

Looking to create an API using Express that is capable of processing requests either through multithreading or multiprocessing. For example, the following API has a 5-second sleep before responding. If I make 3 quick calls to it, the first response will ta ...