We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
最近项目中使用 NodeJS 来读写 .json 文件. NodeJS 支持直接 require( jsonfilepath ), 得到的就是 object. 所以读 json 很容易.
写文件遇到一个这样的问题: json 文件是由人工来维护的, 有相应的编码格式 - 至少不在一行. 开始是这样写文件的:
// 这里不关注同步/异步. fs.writeFile( jsonfilepath, JSON.stringify(object), 'utf8' );
最后得到的文件都在一行, 导致人没法直接读内容 - 需要 format.
在这里看到 JSON.stringify 还有其它参数.
ex1:
JSON.stringify( {a: 'a'} ); // '{"a": "a"}'
ex2:
JSON.stringify( {a: "a", b: "b"}, ['a'] ); // '{"a": "a"}'
ex3:
JSON.stringify( {a: "a", b: "b"}, function( key, value ) { if ( key === 'a' ) return 1; return value; }); // '{"a": 1, "b": "b"}'
ex4:
JSON.stringify( {a: "a", b: "b"}, function( key, value ) { if ( key === 'a' ) return undefined; return value; }); // '{"b": "b"}'
ex5:
JSON.stringify( {a: "a", b: "b"}, null, 2 ); /* '{ "a": "a", "b": "b" }' */
ex6:
JSON.stringify( {a: "a", b: "b"}, null, '\r\n' ); /* "{ "a": "a", "b": "b" }" */
回到正题: fs.writeFile( jsonfilepath, JSON.stringify( object, null, 2 ), 'utf8' );
fs.writeFile( jsonfilepath, JSON.stringify( object, null, 2 ), 'utf8' );
:)
The text was updated successfully, but these errors were encountered:
No branches or pull requests
最近项目中使用 NodeJS 来读写 .json 文件.
NodeJS 支持直接 require( jsonfilepath ), 得到的就是 object. 所以读 json 很容易.
写文件遇到一个这样的问题:
json 文件是由人工来维护的, 有相应的编码格式 - 至少不在一行.
开始是这样写文件的:
最后得到的文件都在一行, 导致人没法直接读内容 - 需要 format.
在这里看到 JSON.stringify 还有其它参数.
ex1:
ex2:
ex3:
ex4:
ex5:
ex6:
回到正题:
fs.writeFile( jsonfilepath, JSON.stringify( object, null, 2 ), 'utf8' );
:)
The text was updated successfully, but these errors were encountered: