fix: json fields not parsed properly (#20866)

* fix: json fields not parsed properly

* fix: prevent stringifying twice
This commit is contained in:
Rémi de Juvigny 2024-07-23 18:27:13 +02:00 committed by GitHub
parent b4ae6aa3c1
commit 41ae36f97c
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 24 additions and 3 deletions

View File

@ -24,7 +24,9 @@ const JsonInput = forwardRef<JSONInputRef, InputProps>(
<Field.Label action={labelAction}>{label}</Field.Label> <Field.Label action={labelAction}>{label}</Field.Label>
<JSONInputImpl <JSONInputImpl
ref={composedRefs} ref={composedRefs}
value={field.value} value={
typeof field.value == 'object' ? JSON.stringify(field.value, null, 2) : field.value
}
onChange={(json) => { onChange={(json) => {
// Default to null when the field is not required and there is no input value // Default to null when the field is not required and there is no input value
const value = required && !json.length ? null : json; const value = required && !json.length ? null : json;

View File

@ -2,18 +2,37 @@ import Field from './field';
export default class JSONField extends Field { export default class JSONField extends Field {
toDB(value: unknown) { 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) { fromDB(value: unknown) {
try { try {
if (typeof value === 'string') { 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) { } catch (error) {
// Just return the value if it's not a valid JSON string // Just return the value if it's not a valid JSON string
return value; return value;
} }
return value; return value;
} }
} }