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; } }