From 41ae36f97ccd4f04837260fd0fbb81fc7cb52e5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9mi=20de=20Juvigny?= <8087692+remidej@users.noreply.github.com> Date: Tue, 23 Jul 2024 18:27:13 +0200 Subject: [PATCH] fix: json fields not parsed properly (#20866) * fix: json fields not parsed properly * fix: prevent stringifying twice --- .../admin/src/components/FormInputs/Json.tsx | 4 +++- packages/core/database/src/fields/json.ts | 23 +++++++++++++++++-- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/packages/core/admin/admin/src/components/FormInputs/Json.tsx b/packages/core/admin/admin/src/components/FormInputs/Json.tsx index 0a4f2b2336..81fe46cd45 100644 --- a/packages/core/admin/admin/src/components/FormInputs/Json.tsx +++ b/packages/core/admin/admin/src/components/FormInputs/Json.tsx @@ -24,7 +24,9 @@ const JsonInput = forwardRef( {label} { // Default to null when the field is not required and there is no input value const value = required && !json.length ? null : json; diff --git a/packages/core/database/src/fields/json.ts b/packages/core/database/src/fields/json.ts index 01600f22ec..c422e3edd4 100644 --- a/packages/core/database/src/fields/json.ts +++ b/packages/core/database/src/fields/json.ts @@ -2,18 +2,37 @@ import Field from './field'; export default class JSONField extends Field { toDB(value: unknown) { - return JSON.stringify(value); + if (value == null) { + return null; + } + + if (typeof value === 'object') { + return JSON.stringify(value); + } + + return value; } fromDB(value: unknown) { try { if (typeof value === 'string') { - return JSON.parse(value); + const parsedValue = JSON.parse(value); + + /** + * On Strapi 5 until 5.0.0-rc.6, the values were accidentally stringified twice when saved, + * so in those cases we need to parse them twice to retrieve the actual value. + */ + if (typeof parsedValue === 'string') { + return JSON.parse(parsedValue); + } + + return parsedValue; } } catch (error) { // Just return the value if it's not a valid JSON string return value; } + return value; } }