简体   繁体   English

在 JavaScript 中将 json 对象写入 .json 文件

[英]Write json object to .json file in JavaScript

var proj = {
    Name : "abc",
    Roll no : 123
};

How can I write proj data in JSON format in.json file in javascript?如何在 javascript 中将 JSON 格式的项目数据写入 .json 文件?

You can save the json object in file.json file like this.您可以像这样将 json 对象保存在 file.json 文件中。

const FileSystem = require("fs");
 FileSystem.writeFile('file.json', JSON.stringify(proj), (error) => {
    if (error) throw error;
  });

JSON.stringify (introduced in ES 5.1) will convert the object into a string of JSON. JSON.stringify (在 ES 5.1 中引入)会将对象转换为 JSON 的字符串。

var json = JSON.stringify(proj);

JavaScript has no built-in mechanism for writing to a file. JavaScript 没有用于写入文件的内置机制。 You generally need something non-standard provided by the host environment.您通常需要宿主环境提供的非标准内容。 For example, Node.js has the writeFile method of the File System module.例如,Node.js 有文件系统模块的writeFile方法。

Pretty much the same as top answer but slightly simpler version I regularly use to help with debugging (prints out an object at a given point in the code without using a debugger):与最佳答案几乎相同但稍微简单一些的版本我经常用来帮助调试(在代码中的给定点打印出一个对象而不使用调试器):

require('fs').writeFile('file.json', JSON.stringify(proj), (error) => {
        if (error) {
            throw error;
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM