【问题标题】:How to capture iterated json values into a variable using javascript如何使用javascript将迭代的json值捕获到变量中
【发布时间】:2020-07-28 13:38:43
【问题描述】:

问题:我想将数据存储到具有动态变化字段的 json 文件中。 假设我想生成以下invoice.json 文件:

{
 "token": "000",
 "invoices":
 [
  {
   "invoiceId": "0001-0001-0001-0001",
   "amount": 45.67
  },
  {
   "invoiceId": "0002-0002-0002-0002",
   "amount": 11.03
  }
 ]
}

理论上我认为以下命令不起作用(为了更好地理解,我对其进行了简化):

const tokenValue = "000"
let invoiceIdValue = ""
let amountValue = ""
for(let i=0; i<1, i++) {
 let data = {
  "token": tokenValue,
  "invoiceId": invoiceIdValue[i] // <- I don't know how to call the 1st index of the field
  "amount": amountValue[i]
 }
}

将其写入变量然后最终写入文件的最易读的方法是什么? 注意:我将使用 cypress 的命令 cy.writeFile('invoice.json', data) 来存储迭代值。

【问题讨论】:

  • 您要创建发票数组,并且令牌在预期的 json 中只有一次,因此令牌不应该在循环中
  • 对不起,但这并没有回答我的问题。出于演示目的,我包含了一个固定变量。我可以使用 cy.writeFile('invoice.json', { token: '000', Invoices[0]: data} ) 之类的东西,但正如我所说,这不是我的问题。

标签: javascript arrays json cypress


【解决方案1】:

首先创建invoices 数组,然后将其嵌入到数据结构中...

const tokenValue = "000";
let invoiceIds = [1, 2, 3];
let amounts = [10, 20, 30];

// Create invoices array first
const invoices = [];
for (let i = 0; i < invoiceIds.length; i++) {
  invoices.push({invoiceId: invoiceIds[i], amount: amounts[i]});
}

// ...then build data structure
const data = {token: tokenValue, invoices};

// Then save to file (or just log, as we're doing here)
console.log('invoice.json', data);

【讨论】:

  • 感谢@broofa,我会对此表示赞同。我认为我过度简化了问题,但希望您仍然可以阐明这一点:如果我需要动态更改值(而不是像上面数组中的固定值),我将如何实现这一点。对于上下文,我使用的是 faker & uuid(节点),所以我也需要迭代金额值(通过 faker.commerce.price())和发票 ID(通过 uuid())。
【解决方案2】:

这样,您可以使用 javascript 将动态 JSON 下载为文件。

var json = {
 "token": "000",
 "invoices":
 [
  {
   "invoiceId": "0001-0001-0001-0001",
   "amount": 45.67
  },
  {
   "invoiceId": "0002-0002-0002-0002",
   "amount": 11.03
  }
 ]
};

function downloadJsonFile(obj, fileName){
    var str = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj));
    var anchor = document.createElement('a');
    anchor.setAttribute("href",     str);
    anchor.setAttribute("download", fileName + ".json");
    document.body.appendChild(anchor);
    anchor.click();
    anchor.remove();
  }
  
downloadJsonFile(json, "json_file_name");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-06
    • 2016-05-01
    • 1970-01-01
    • 2013-09-19
    • 2022-11-25
    相关资源
    最近更新 更多