writeJSON reorganizes file?

I have a draft containing JSON. When I use writeJSON in a Draft action, the resulting file is not organized the same as what I see in my draft.

If the draft is:

{
    "Fruit Number": 1,
    "Fruit Name": "apple",
    "Fruit Types": [
        {
            "Type": "Golden Delicious",
            "Type Number": 1
        },
        {
            "Type": "Granny Smith",
            "Type Number": 2
        }
    ],
    "Has Seeds": true
}

When I write the file using writeJSON, the file is:

{
    "Fruit Number": 1,
    "Fruit Types": [
        {
            "Type": "Golden Delicious",
            "Type Number": 1
        },
        {
            "Type": "Granny Smith",
            "Type Number": 2
        }
    ],
    "Fruit Name": "apple",
    "Has Seeds": true
}

“Fruit Name” has jumped down the list to above “Has Seeds.” Not the biggest deal in terms of parsing JSON, but using a diff function in Visual Studio Code, it’s registering the position change as a change, when I’d really only like to see real content changes.

Anything I’m doing wrong here or could be doing differently so that the exported draft looks exactly like what I’m seeing in Drafts? I can use writeString instead, but then slashes aren’t escaped and the spacing around colons is a little different, and I end up with the same problem in the diff editor.

Thanks all!

When working with JSON, you are ultimately working with JavaScript objects - which are keys and associated values, but have no inherent ordering to the keys, so anytime you access the keys, such as to write them out to a JSON file, they could come back in a different order.

If reliable ordering is important, you might need to use a different strategy for data storage.

If could structure your data in arrays instead of objects, they do have inherent ordering to them. Not sure if that’s logical, however.

Thank you! I’ll work with it and see if I can figure a strategy that meets my workflow. Appreciate the speedy response!

Note that if that is string content you have in a draft, you can use writeString to write it to a .json file and the content will not be altered. JSON is a string format, so if you are not passing it through being parsed as a JavaScript object, you will not have that problem.

1 Like