通过javascript删除json中相邻的重复数字

q3aa0525  于 2023-02-15  发布在  Java
关注(0)|答案(2)|浏览(155)

我的json:

  1. { "question_1":
  2. { "type" : "string"
  3. , "title" : "1. 1. What did he want to make for dinner?"
  4. , "enum":
  5. [ " a.) He wanted to make some salad and spaghetti"
  6. , " b.) He wanted to make some pasta salad"
  7. ]
  8. , "required": false
  9. }
  10. , "question_2":
  11. { "type": "string"
  12. , "title": "2. 2. Did he have the ingredients to make dinner?"
  13. , "enum":
  14. [ " a.) Yes, he had the ingredients"
  15. , " b.) No, he didn't have the ingredients"
  16. ]
  17. , "required": false
  18. }
  19. , "question_3":
  20. { "type" : "string"
  21. , "title" : "3. 3. Where did he go shopping?"
  22. , "enum":
  23. [ " a.) He went to Albertsons"
  24. , " b.) He went to Albertos"
  25. ]
  26. , "required": false
  27. }
  28. }

在我的json中有许多数字彼此相邻并且重复
例如:

  1. 1. 1. => 1.
  2. 2. 2. => 2.
  3. 3. 3. => 3.

等等
我如何删除此重复项?
我想删除json中相邻的重复数字

b4lqfgs4

b4lqfgs41#

你可以用正则表达式替换它,使用分组引用((\d)周围的括号形成一个小数组,\1引用它)将确保你不会删除像“1.2.”这样的数字,并允许你在替换过程中引用它:

  1. const data =
  2. { "question_1":
  3. { "type" : "string"
  4. , "title" : "1. 1. What did he want to make for dinner?"
  5. , "enum":
  6. [ " a.) He wanted to make some salad and spaghetti"
  7. , " b.) He wanted to make some pasta salad"
  8. ]
  9. , "required": false
  10. }
  11. , "question_2":
  12. { "type": "string"
  13. , "title": "2. 2. Did he have the ingredients to make dinner?"
  14. , "enum":
  15. [ " a.) Yes, he had the ingredients"
  16. , " b.) No, he didn't have the ingredients"
  17. ]
  18. , "required": false
  19. }
  20. , "question_3":
  21. { "type" : "string"
  22. , "title" : "3. 3. Where did he go shopping?"
  23. , "enum":
  24. [ " a.) He went to Albertsons"
  25. , " b.) He went to Albertos"
  26. ]
  27. , "required": false
  28. }
  29. };
  30. Object.values(data).forEach(v => v.title = v.title.replace(/(\d)\. \1\./, '$1.'))
  31. console.log(Object.values(data).map(v => v.title))
展开查看全部
yi0zb3m4

yi0zb3m42#

如果它实际上是JSON(您将使用JSON.parse解析它),则可以使用可选的reviver参数。

复苏剂

如果是函数,则指定解析最初生成的每个值在返回之前如何转换。不可调用的值将被忽略。函数使用以下参数调用:

按键

与值关联的键。

数值

分析生成的值。

  1. const JSONString = `{
  2. "question_1": {
  3. "type": "string",
  4. "title" : "1. 1. What did he want to make for dinner?"
  5. },
  6. "question_2": {
  7. "type": "string",
  8. "title": "2. 2. Did he have the ingredients to make dinner?"
  9. }
  10. }`;
  11. console.log(
  12. JSON.parse(JSONString, (key, value) => typeof value === 'string' ? value.replace(/(\d)\. \1\./, '$1.') : value)
  13. )

扩展Moritz Ringler的解决方案。

展开查看全部

相关问题