I have a JSON file that I’m reading data from for a Playwright test as below:
async answerMyDetails(){
const testDataFile = './myJsonFile.json'
let data = await fs.readFile(testDataFile)
let testData = await JSON.parse(data)
await this.page.locator(`div:has(> label:has-text("Some Text")) input`).fill(`${testData.myDetailsPageQuestions.vehicleReg.answer_fullUkLicence_carInsurance}`)
}
I’d like to change this so that the _fullUkLicence_carInsurance part of the property that’s being read from the JSON file is not hard coded and can be determined at the time the function is called, e.g. something like:
(answerSet == fullUkLicence_carInsurance)
async answerMyDetails(answerSet){
const testDataFile = './myJsonFile.json'
let data = await fs.readFile(testDataFile)
let testData = await JSON.parse(data)
await this.page.locator(`div:has(> label:has-text("Some Text")) input`).fill(`${testData.myDetailsPageQuestions.vehicleReg.answer_{answerSet}}`)
}
2
Answers
To make the property you’re accessing from the JSON file dynamic, you can use bracket notation in JavaScript. This lets you access an object’s properties based on a variable rather than hard-coding the property key. Here’s how you can update your function:
And here is the explanation on what’s going on here:
By using answer[answerSet], you can pass the key you want (fullUkLicence_carInsurance, for example) as a parameter when you call the function. This avoids hard-coding the property name and makes it more flexible.
So, when you call answerMyDetails(‘fullUkLicence_carInsurance’), it will dynamically fill the input field with the corresponding value from your JSON file.
Hope this helps! Let me know if you have any questions.
You can use bracket notation instead of dot notation to dynamically reference an object property name.