step 1: 存储JSON数据到.json文件
const book = {
title: "Ego is enemy",
author: "Ryan Holiday",
};
const bookJSON = JSON.stringify(book);
fs.writeFileSync("1-json.json", bookJSON);
这一步骤将生成文件1-json.json:
{"title":"Ego is enemy","author":"Ryan Holiday"}
step 2: 从生成的.json文件读取JSON 数据
const fs = require("fs");
const dataBuffer = fs.readFileSync("1-json.json");
const bookJSON = dataBuffer.toString();
const book = JSON.parse(bookJSON);
console.log(book.title);
console.log(book.author);
dataBuffer 是二进制数据,JSON.parse() 和 JSON.stringify() 互为逆操作。parse 解析 JSON 为对象,stringify 生成对象的JSON 字符串表示。
输出如下:
Ego is enemy
Ryan Holiday