问题
I've have structure like below from response
{
"last UpdatedTime":"18:00:01 AM",
"has PErmission":false,
"block UsersSubFeatures":true,
"block CurrentUserTill":"NA",
"unlock UserOnlyForVisibility":"['departmentXYZ']"
}
Note: "unlockUserOnlyForVisibility":"['departmentXYZ']" // array in as string. But want to convert like
{
"last UpdatedTime":"18:00:01 AM",
"has PErmission":false,
"block UsersSubFeatures":true,
"block CurrentUserTill":"NA",
"unlock UserOnlyForVisibility":['departmentXYZ']
}
so i tried JSON.parse(), which gives me Unexpected syntaxError: unexpected token of in JSON at position 1 [Object object ]
so tried regex like below which successfully removes quotes. but not sure this is the proper way to handle this or not
Thanks for the help
回答1:
As Olyno mentioned, clearly this is something that needs to be fixed backend.
That being said, you need to replace "[
with just [
and ]"
with ]
, then handle the single quotes of the elements seperately.
const response = `{
"last UpdatedTime":"18:00:01 AM",
"has PErmission":false,
"block UsersSubFeatures":true,
"block CurrentUserTill":"NA",
"unlock UserOnlyForVisibility":"['hello world', 'test2']"
}`
function cleanBrokenJSONObject(data) {
return data
.replace(/"\[([^\]]*)\]"/g, function(_, singleQuoteElements){
const elements = singleQuoteElements.replace(/'/g, '"');
return `[${elements}]`
})
}
const res = cleanBrokenJSONObject(response);
console.log(JSON.parse(res));
note: this will only work with an array of depth 1 and not more
Break down of the regex: /"\[([^\]]*)\]"/g
"\[
match string that starts with"[
([^\]]*)
Capture all the next characters and stop when encountering]
(this is essentially the elements of your array)\]"
match string that ends with]"
When we capture the elements of the list (2), we replace all the '
with "
.
Test cases:
const list1 = `"['hello world', 'test2']"`;
const list2 = `"['','']"`
const list3 = `"['']"`
const list4 = `"[]"`
function cleanBrokenJSONObject(data) {
return data
.replace(/"\[([^\]]*)\]"/g, function(a,b){
const elements = b.replace(/'/g, '"');
return `[${elements}]`
})
}
[list1, list2, list3, list4].forEach(list => {
const res = cleanBrokenJSONObject(list);
console.log(JSON.parse(res));
});
回答2:
The right way to fix that is to fix your backend, and how you generate and manage the value. If you really want to fix it using your frontend, you need 2 steps:
- Convert singles quotes in double quotes
- Convert the given string to an object using JSON.parse
So to make these steps, you need this code:
JSON.parse("['departmentXYZ']".replace(/'/g, '"')); // ["departmentXYZ"]
来源:https://stackoverflow.com/questions/64771289/how-to-remove-quotes-from-object-response-for-particular-key-value-and-return-th