sort object properties and JSON.stringify

后端 未结 22 2320
南方客
南方客 2020-11-28 05:44

My application has a large array of objects, which I stringify and save them to the disk. Unfortunately, when the objects in the array are manipulated, and sometimes replac

22条回答
  •  半阙折子戏
    2020-11-28 06:04

    You can add a custom toJSON function to your object which you can use to customise the output. Inside the function, adding current properties to a new object in a specific order should preserve that order when stringified.

    See here:

    https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify

    There's no in-built method for controlling ordering because JSON data is meant to be accessed by keys.

    Here's a jsfiddle with a small example:

    http://jsfiddle.net/Eq2Yw/

    Try commenting out the toJSON function - the order of the properties is reversed. Please be aware that this may be browser-specific, i.e. ordering is not officially supported in the specification. It works in the current version of Firefox, but if you want a 100% robust solution, you may have to write your own stringifier function.

    Edit:

    Also see this SO question regarding stringify's non-deterministic output, especially Daff's details about browser differences:

    How to deterministically verify that a JSON object hasn't been modified?

提交回复
热议问题