【问题标题】:How to add new keys and values to a json from a txt file in node.js如何从 node.js 中的 txt 文件向 json 添加新的键和值
【发布时间】:2021-04-24 20:28:06
【问题描述】:

从一个带有值但没有键的 txt 文件中,我想将这些值添加到一个空的 json 文件中。我必须为每个值添加键,保存 json 文件并将 json 文件导出到新的 txt,这次使用键。

所以我有这个 json 文件

{ "agenda" : []
}

我有这个 txt 文件(所有假数据,以防你想知道):

"Fidel","Oltra","fidel@gmail.com","6650403234"
"Merxe","Sanz","merxe@gmail.com","65345235"
"David","Garcia","dgarcia@gmail.com","69823422"
"Amparo","López","alopez@gmail.com","67234234"
"Antonio","Gómez","antoniog@gmail.com","69929292"

我希望 json 文件看起来像

{
   "agenda":[
      {
         "Name": "Fidel",
         "Surname": "Oltra",
         "Email": "fidel@gmail.com",
         "Phone": 6650403234
      },
      {
         ...
      },
      ...
   ]
}

我的这段代码可以正常工作,但我不知道如何正确推送数据,因为最终的 json 文件看起来不像预期的那样。

const archivo = require("fs");
const json = require("fs");

const file = archivo.readFileSync('agenda.txt', 'utf8');
console.log(file);
const lines = file.split('\n');
console.log(lines);
let campos;

let rawdata = json.readFileSync('agenda.json');
let json1 = JSON.parse(rawdata);
console.log(json1);

for (i in lines) {
    campos = lines[i].split(",");
    json1.agenda.push('Nombre:', campos[0]);
    json1.agenda.push('Apellido:', campos[1]);
    json1.agenda.push('Email:', campos[2]);
    json1.agenda.push('Teléfono:', campos[3]);
    console.log(campos);
    console.log(json1);

};

let data = JSON.stringify(json1);
json.writeFileSync('agenda2.json', data);

当我打开它时的 json 是:

{"agenda":["Nombre:","\"Fidel\"","Apellido:","\"Oltra\"","Email:","\"fidel@gmail.com\"","Teléfono:","\"6650403234\"\r","Nombre:","\"Merxe\"","Apellido:","\"Sanz\"","Email:","\"merxe@gmail.com\"","Teléfono:","\"65345235\"\r","Nombre:","\"David\"","Apellido:","\"Garcia\"","Email:","\"dgarcia@gmail.com\"","Teléfono:","\"69823422\"\r","Nombre:","\"Amparo\"","Apellido:","\"López\"","Email:","\"alopez@gmail.com\"","Teléfono:","\"67234234\"\r","Nombre:","\"Antonio\"","Apellido:","\"Gómez\"","Email:","\"antoniog@gmail.com\"","Teléfono:","\"69929292\""]}

所以我想要一些帮助以使其正常工作并了解我做错了什么......并且还想知道如何将正确的最终 json 写回 txt 文件。

【问题讨论】:

  • 将粘贴在输入中或将由服务接收的“假数据”?
  • 抱歉,我好像没听懂问题
  • 我在询问您放入上述脚本(文本文件)中的数据将始终是文本文件吗?永远不会改变?
  • 是的,它将是一个文本文件

标签: javascript node.js json txt


【解决方案1】:

我发现了两个问题。

  1. 您从未从 agenta.txt 中删除引号 / cotizaciones。这意味着您的结尾 json 正在为您转义引号。 "String" 在 JSON 中是 "\"String\""
  2. 在 for 循环中,您将键和值推送到数组中,而不是创建对象,然后将该对象推送到数组中。
const fs = require("fs");

const file = fs.readFileSync("agenda.txt", "utf8");
console.log(file);
const sinCotiz = file.replace(/"/g, ""); // remove quotes
const lines = sinCotiz.split("\n");
console.log(lines);

const rawdata = fs.readFileSync("agenda.json");
const json1 = JSON.parse(rawdata);
console.log(json1);

for (i in lines) {
  const obj = {}; // create an object
  const campos = lines[i].split(",");
  obj["Nombre"] = campos[0]; // create keys and values for the object
  obj["Apellido"] = campos[1];
  obj["Email"] = campos[2];
  obj["Teléfono"] = campos[3];
  json1.agenda.push(obj); // push the entire object in the array
  console.log(campos);
  console.log(json1);
}

const data = JSON.stringify(json1);
fs.writeFileSync("agenda2.json", data);

【讨论】:

    【解决方案2】:

    我认为有更简单的解决方案, 但您可以格式化您的文件,因为它是 CSV 文件。您将首先放置一个图层以删除 '' 并更改 ; ,那么你需要在你的情况下添加一个标题行,标题将是

    Nombre;Apellido;Email;Teléfono

    然后你使用这个功能:

    function csvJSON(csv){
    
      var lines=csv.split("\n");
    
      var result = [];
    
      var headers=lines[0].split(",");
    
      for(var i=1;i<lines.length;i++){
    
          var obj = {};
          var currentline=lines[i].split(",");
    
          for(var j=0;j<headers.length;j++){
              obj[headers[j]] = currentline[j];
          }
    
          result.push(obj);
    
      }
      
      //return result; //JavaScript object
      return JSON.stringify(result); //JSON
    }
    

    这将为您提供具有以下结构的格式化 json:

    [{Nombre:4444,Apellido:"AAAA",....}]

    您可以将整个功能直接放在您的议程中:)

    我再次认为有更简单的解决方案,但也许这会有所帮助。

    【讨论】:

      【解决方案3】:
      const archivo = require("fs");
      const json = require("fs");
      
      const file = archivo.readFileSync('agenda.txt', 'utf8');
      
      const lines = file.split('\n');
      
      let campos;
      
      let rawdata = json.readFileSync('agenda.json');
      let json1 = JSON.parse(rawdata);
      
      for (i in lines) {
          if(lines[i]) {
             campos = lines[i].split(",");
             let payload = {
              'Name' : campos[0].substr(1,campos[0].length-2), // to remove double quotes from the string
              'Surname' : campos[0].substr(1,campos[0].length-2),
              'Email' : campos[0].substr(1,campos[0].length-2),
              'Phone' : campos[0].substr(1,campos[0].length-2),
             }
             json1.agenda.push(payload);
           }
         };
      
      let data = JSON.stringify(json1);
      json.writeFileSync('agenda2.json', data);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-01
        • 2018-10-06
        • 1970-01-01
        • 1970-01-01
        • 2021-08-03
        相关资源
        最近更新 更多