Max Schmitt

February 16 2024

Sanity: How to Edit Documents as JSON

Have you ever tried to change the name of a type in Sanity and encountered one of the following errors?

  • "Item of type someType not valid for this list"
  • "Invalid property value: The property value is stored as a value type that does not match the expected type"
Sanity error: Invalid property value: The property value is stored as a value type that does not match the expected type

Why does this happen?

Errors like the ones above happen because existing values still reference the old type.

For example, if you have a custom type called person and you want to change it to user, you will need to update any references to person in your documents, even if user has the same structure as person.

Wouldn't be nice if we could edit the documents as JSON and do a simple find and replace?

Sanity actually allows you to do that, even though the feature is a little bit hidden. Here's how:

How to edit the JSON representation of a document in Sanity

Make sure to navigate to your project's repository and the run the following command using the Sanity CLI:

sanity documents create --id <document-id> --replace

The command looks a bit confusing / scary ("create" and "--replace") but the built-in help explains these options:

Terminal

$ npx sanity documents create --help
usage: sanity documents create [FILE]
Create one or more documents
Options
--replace On duplicate document IDs, replace existing document with specified document(s)

How to get a Sanity document's ID

You can get the document ID from the URL when you open the document in the Sanity Studio:

https://example.com/studio/structure/contentPage;5d8533c4-19fb-47c0-b76d-8b40ac3395f4
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Edit Sanity document in VS Code

By default, the sanity documents create command will open the document in the default $EDITOR. On most machines, this is vim or nano.

If you want to use VS Code, you can set it as the default editor by running the following command:

Terminal

$ EDITOR='code --wait' npx sanity documents create --id <document-id> --replace

After closing the editor of your choice, the document will be updated in the Sanity Studio:

Terminal

$ sanity documents create --id 5d8533c4-19fb-47c0-b76d-8b40ac3395f4 --replace
Upserted:
- 5d8533c4-19fb-47c0-b76d-8b40ac3395f4

If you close the editor without making any changes, Sanity will give you feedback accordingly:

Terminal

$ sanity documents create --id 5d8533c4-19fb-47c0-b76d-8b40ac3395f4 --replace
Value not modified, doing nothing.
Modify document to trigger creation.

Conclusion

I hope this guide helped you out. I find it very useful to edit document as JSON for simple data migrations or renaming types.