Node JS 对象和 JSON 文件相互转换

JSON 文件转换成 JS 对象

直接使用 noderequire() 方法即可将 JSON 文件转换成 JS 对象:

// test.json
{
  "name": "张三",
  "age": 22
}
// test.js
const test = require('./test.json')
console.log(test)
$ node test
{ name: '张三', age: 22 }

JS 对象转换成 JSON 文件

使用 JSON.Stringify() 方法和 node 创建文件方法 fs.writeFileSync()

const fs = require('fs')

// 待转换的对象
const lisi = {
  name: '李四',
  age: 25,
  friends: ['张三', '王五', '赵六']
}

fs.writeFileSync('lisi.json', JSON.stringify(lisi))
// lisi.json
{"name":"李四","age":25,"friends":["张三","王五","赵六"]}
原文地址:https://www.cnblogs.com/haveadate/p/14817334.html