PrismaP
Prisma2y ago
2 replies
slower_loris

Preserve key order when writing JSON fields

I am using Prisma with Postgres and I have the following JSON data that I want to insert into my table:
{"First Section":[{"title":"Heading 1","body":"Body 1"}],"Second Section":[{"title":"Heading 2","body":"Body 2"}],"Final Section":[{"title":"Heading 3","body":"Body 3"}]}

To save it to my database, I'm using upsert:
prisma.pages.upsert({
  where: {
    title: 'page001',
   },
  update: {
    layouts: {"First Section":[{"title":"Heading 1","body":"Body 1"}],"Second Section":[{"title":"Heading 2","body":"Body 2"}],"Final Section":[{"title":"Heading 3","body":"Body 3"}]}
 },
create: {
  layouts: {"First Section":[{"title":"Heading 1","body":"Body 1"}],"Second Section":[{"title":"Heading 2","body":"Body 2"}],"Final Section":[{"title":"Heading 3","body":"Body 3"}]}
 }
});


When I then query that record, I get the JSON returned with the following key order:
{
  "Final Section": [
    {
      "body": "Body 3",
      "title": "Heading 3"
    }
  ],
  "First Section": [
    {
      "body": "Body 1",
      "title": "Heading 1"
    }
  ],
  "Second Section": [
    {
      "body": "Body 2",
      "title": "Heading 2"
    }
  ]
}


Is there any way to preserve the order of the keys when writing the data to postgres?
Solution
I ended up solving this in a way that didn't require me to have the keys written in a specific order.
Was this page helpful?