如何从对象响应中删除特定键值的引号并返回相同的结构 [英] how to remove quotes from object response for particular key value and return the same structure

查看:36
本文介绍了如何从对象响应中删除特定键值的引号并返回相同的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据回复,我具有以下结构

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']"
    
}

注意:"unlockUserOnlyForVisibility":"['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']
    
}

所以我尝试了JSON.parse(),这给了我意外语法错误:位置1的JSON中的意外标记[对象对象]

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

感谢您的帮助

推荐答案

正如Olyno所说,显然这是需要固定的后端.

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

注意:这仅适用于深度为1且不大于1的数组

分解正则表达式:/"\ [([^ \]] *)\]"/g

  1. " \\ 匹配以" [
  2. 开头的字符串
  3. ([[^ \]] *)捕获所有下一个字符并在遇到] 时停止(这实际上是数组的元素)
  4. \]''>匹配以]''
  5. 结尾的字符串
  1. "\[ match string that starts with "[
  2. ([^\]]*) Capture all the next characters and stop when encountering ] (this is essentially the elements of your array)
  3. \]" match string that ends with ]"

当我们捕获列表(2)的元素时,我们将所有'替换为'''.

When we capture the elements of the list (2), we replace all the ' with ".

测试用例:

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

这篇关于如何从对象响应中删除特定键值的引号并返回相同的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆