mirror of
https://github.com/strapi/strapi.git
synced 2025-08-30 19:56:05 +00:00
fix: json fields not parsed properly (#20866)
* fix: json fields not parsed properly * fix: prevent stringifying twice
This commit is contained in:
parent
b4ae6aa3c1
commit
41ae36f97c
@ -24,7 +24,9 @@ const JsonInput = forwardRef<JSONInputRef, InputProps>(
|
||||
<Field.Label action={labelAction}>{label}</Field.Label>
|
||||
<JSONInputImpl
|
||||
ref={composedRefs}
|
||||
value={field.value}
|
||||
value={
|
||||
typeof field.value == 'object' ? JSON.stringify(field.value, null, 2) : field.value
|
||||
}
|
||||
onChange={(json) => {
|
||||
// Default to null when the field is not required and there is no input value
|
||||
const value = required && !json.length ? null : json;
|
||||
|
@ -2,18 +2,37 @@ import Field from './field';
|
||||
|
||||
export default class JSONField extends Field {
|
||||
toDB(value: unknown) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
Loading…
x
Reference in New Issue
Block a user