Skip to content
New issue

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

读写 JSON 文件 #73

Open
zhanhongtao opened this issue Dec 29, 2013 · 0 comments
Open

读写 JSON 文件 #73

zhanhongtao opened this issue Dec 29, 2013 · 0 comments

Comments

@zhanhongtao
Copy link
Owner

最近项目中使用 NodeJS 来读写 .json 文件.
NodeJS 支持直接 require( jsonfilepath ), 得到的就是 object. 所以读 json 很容易.

写文件遇到一个这样的问题:
json 文件是由人工来维护的, 有相应的编码格式 - 至少不在一行.
开始是这样写文件的:

// 这里不关注同步/异步.
fs.writeFile( jsonfilepath, JSON.stringify(object), 'utf8' );

最后得到的文件都在一行, 导致人没法直接读内容 - 需要 format.

这里看到 JSON.stringify 还有其它参数.

  1. JSON.stringify( object, list ); 表示只转 list 中的属性 - 白名单.
  2. JSON.stringify( object, translate ); 在转义时, 对属性先做处理.
  3. JSON.stringify( object, list, format ); 格式化字符串.

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' );

:)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant