【问题标题】:Saving a JSON object into a file in Node [duplicate]将 JSON 对象保存到 Node 中的文件中 [重复]
【发布时间】:2020-02-24 22:25:55
【问题描述】:

我已经阅读过类似的问题,但我找不到解决方案。我正在将 CSV xml 文件转换为 json 对象数组。以下函数成功完成:

const csvtojsonV2 = require("csvtojson");

csvtojsonV2().fromFile('./CSV_TO_JSON/file.xml')
    .then((jsonObj) => {

        console.log(jsonObj)

    })

但现在我想获取该 jsonObj 并将其放入我当前工作区文件夹内的文件中:

const uuidv1 = require('uuid/v1')
const fs = require('fs')
const path = require('path')

csvtojsonV2().fromFile('./CSV_TO_JSON/file.xml')
    .then((jsonObj) => {

        var folderNameJSON = uuidv1()
        folderNameJSON = 'JSON_CONVERTED'

        fs.mkdirSync(folderNameJSON)
        fs.writeFileSync(path.join(__dirname, folderNameJSON, 'file.json'), jsonObj)


    })

但是当我打开文件时,它只是出现:[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],etc...

¿这是应该的样子吗?如何使它显示为对象数组,就像我在第一个代码 sn-p 中 console.log(jsonObj) 时出现的那样?

【问题讨论】:

  • 你试过JSON.stringify(jsonObj)吗?

标签: javascript node.js json


【解决方案1】:

在保存到文件之前使用 JSON.stringify 将 json 转换为字符串 https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/JSON/stringify

【讨论】:

    【解决方案2】:

    要写入文件,您必须将对象转换为字符串。

    随便用

    let objString = JSON.stringify(jsonObj);
    fs.writeFileSync(path.join(__dirname, folderNameJSON, 'file.json'), objString);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-08
      • 2016-08-15
      • 2021-04-08
      • 2015-05-31
      • 2013-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多