Skip to content

读写 JSON 文件  #73

Open
Open
@zhanhongtao

Description

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

:)

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @zhanhongtao

        Issue actions

          读写 JSON 文件 · Issue #73 · zhanhongtao/blog