尝试将此字符串转换为对象

3

I have this string:

posts{id,title},posts2{id,title}

我将其转换为一个对象:
{
  posts: [
    'id', 
    'title'
  ],
  posts2: [
    'id', 
    'title'
  ]
}

我该如何做到这一点?


输入字符串的语法是什么?请至少提供一些有效(和无效)输入的示例。 - Wyck
2个回答

1
这段代码可以处理一级对象,如果你需要解析嵌套的对象,你需要稍微重构它。
const input = 'posts{id,title},posts2{id,title}';

const parse = (input) => {
  return input
    .replaceAll('{', '[')
    .replaceAll('}', ']')
    .replaceAll('],', '] , ')
    .split(' , ')
    .reduce((_, item) => {
      const key = item.split('[')[0];
      const value = item
        .replace(`${key}[`, '')
        .replace(']', '')
        .split(',')
      return {
        ..._,
        [key]: value
      };
    }, {})
};

const parsed = parse(input);

无论如何,我不知道处理这个符号有什么好处。


1

假设字符串符合指定的格式:

您可以将字符串拆分为键-列表项对。 然后,遍历它们并将每个插入对象中,如下所示:

const stringify = string => {
  const obj = {};
  if(string) {
    const pairs = string.substring(0,string.length-1).split('},');
    pairs.forEach(pair => {
      const [key,value] = pair.split('{');
      obj[key] = value.split(",").filter(String);
    });
  }
  return obj;
}

console.log( stringify('posts{id,title},posts2{id,title}') );
console.log( stringify('posts{id,title}') );
console.log( stringify('posts{}') );
console.log( stringify('') );


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接