【问题标题】:Fix wrong json format javascript or regex修复错误的 json 格式 javascript 或 regex
【发布时间】:2020-08-07 08:36:49
【问题描述】:

我有 json 文件,但是 require("./screens/test/test.jsx") 附近的 json 文件格式错误,我需要通过 javascript 修复这个错误的 json 格式

我尝试了一个 json 格式化程序网站,该网站正在修复我错误的 json 格式。但我无法从 javascript 修复这种 json 格式

你可以通过这个https://jsonformatter.curiousconcept.com/修复这个错误的json

[
  {
    "screenName": "screen1",
    "path": "path1",
    "componentPath": require('./screens/test/test.jsx')
   },
   {
    "screenName": "screen1",
    "path": "path1",
    "componentPath": require('./screens/test/test.jsx')
   }
]

从上面应该得到的是:

[
  {
    "screenName": "screen1",
    "path": "path1",
    "componentPath": "require('./screens/test/test.jsx')"
   },
   {
    "screenName": "screen1",
    "path": "path1",
    "componentPath": "require('./screens/test/test.jsx')"
   }
]

【问题讨论】:

  • 我不明白。您是要修复错误的 json,还是编写一个修复错误 json 的 javascript 函数?
  • @DevOfZot 我想写个js函数来修复这种类型的json
  • 这或多或少相当于写一个 JSON 解析器,相当复杂。您最好的选择是在 try-catch 中执行“JSON.parse(string)”,如果它发现错误,请使用正则表达式修复您之前看到的已知错误。

标签: javascript node.js json regex


【解决方案1】:
  1. 将您的 json 声明为文本;
  2. 使用 replace() 对您的所有要求进行字符串化;
  3. 解析你的安全 json。
var json = `
 [
  {
    "screenName": "screen1",
    "path": "path1",
    "componentPath": require('./screens/test/test.jsx')
   },
   {
    "screenName": "screen1",
    "path": "path1",
    "componentPath": require('./screens/test/test.jsx')
   }
 ]
`;

json = json.replace(/require[(]/g, '"require(').replace(/[)]/g, ')"');

json = JSON.parse(json); // your safe json is here

【讨论】:

  • Maycon 有时 require 带有双引号 require("./screens/test/test.jsx")。然后 JSON 解析失败
  • replace 正在全局替换 require 但我不想全局替换 require 因为 screenName 可能有类似这样的 require 关键字 { "screenName": "requireDemoGraphic", "path": "", "componentPath":要求(“./screens/test/test.jsx”)}
  • 嗨@MuhammadNuman。即使在对象道具名称中使用了“require”字样,我也修改了代码(替换行)以使其正常工作。试试看是否可行
  • 但是,使用双引号的 require("./screens/test/test.jsx") 也可以!试试吧。
  • 它不工作。它给了我 JSON 解析错误
猜你喜欢
  • 1970-01-01
  • 2012-10-25
  • 2011-10-18
  • 1970-01-01
  • 2015-12-31
  • 1970-01-01
  • 2011-10-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多