【问题标题】:Replace double quotes with graves in a string without creating a new string用字符串中的坟墓替换双引号而不创建新字符串
【发布时间】:2020-02-12 05:32:28
【问题描述】:

我有一个 json,我在其中存储了一个带有链接的属性。我想将其写入 .txt 文件,以便我可以复制内容并将其用于资源对象中,该资源对象具有我想使用template literals 注入的 serverUrl 变量。在此之前,我需要稍微更改 JSON 的字符串值,以便可以使用模板文字。

json对象的格式如下:

{
  "products": [
    {
      "image": "http://test.test.com/images/imageName.jpg"
    },
    {
      "image": "http://test.test.com/images/imageName2.jpg"
    }
  ]
}

我想要实现的是将每个图像值更改为每个产品对象的以下格式:

`http://${serverUrl}/images/imagename`

在创建 json 期间,我设法使用简单的 string.replace() 替换了 url,但我在以下步骤中苦苦挣扎:

  1. 将双引号改为graves ("" => ``) 并保留url。
  2. 全局执行,我不想提取值,应该覆盖对象。

我尝试过编写一些正则表达式,但我似乎无法弄清楚如何替换双引号并将网址保留在一个正则表达式中。 这是解决这个问题的正确方法吗?或者我应该尝试一些完全不同的东西

编辑

到目前为止我的代码

let dataImport = [];

// Code to convert excel to JSON
// Contains the following line for the image property
case "image": 
  value = value.replace("https://test.test.com", "${serverUrl}");
  rowData["image"] = value;
break;

// Convert object
let json = JSON.stringify(dataImport, null, 2);
fs.writeFileSync("data.txt", json);

【问题讨论】:

  • 在 JSON 中使用反引号会使 JSON 无效。
  • 你有 JSONobject 吗? JSON 是一种用于序列化 objects 的文本格式,看起来类似于 JavaScript 中的 对象文字,但是反引号在其中不是有效的语法。对象是纯 JS 文字,它允许任何 JS 语法,包括反引号。话虽如此,遇到时会评估模板文字,您不能“存储”`Hello ${name}` 之类的内容,然后再执行评估。例如,您可以将其放入接受 name 的函数中,从而在调用时计算表达式。
  • 在我的对象上调用 JSON.stringify() 后,我试图对字符串值进行此替换。这会绕过这个问题吗?我并没有尝试实际使用 JSON,我只是想将替换的结果写入 .txt 文件。
  • “我并没有尝试实际使用 JSON,我只是想将替换的结果写入 .txt 文件。” 我假设您将在不知何故。你打算怎么做?
  • 您可以在完成JSON.stringify 后更改您获得的内容,然后将数据写入文件。但是,之后您在读取文件时需要一个自定义解析器,因为您将不再拥有 JSON。你会有一些近似于 JSON 的东西,但会导致所有 JSON 解析器在读取它时出错。如果你真的想要的话,你最好在序列化/反序列化时使用基本的字符串替换。因此,您可以将任何 URL 转换为 "http://${serverUrl}/images/imagename"(或您选择的任何自定义模板标记),然后在读取时将其替换回来。

标签: javascript json regex


【解决方案1】:

var json = JSON.stringify({
  "products": [
    {
      "image": "http://test.test.com/images/imageName.jpg"
    },
    {
      "image": "http://test.test.com/images/imageName2.jpg"
    }
  ]
}, null, '  ');

var domain = "test.test.com";
console.log(convertJsonUrls(json, domain));

/**
 * Converts any strings containing urls for the specified domain into template-strings,
 * and replaces the domain with '${serverUrl}'
 */
function convertJsonUrls(json, domain) {
    var stringRE = /"((?:\\.|[^\\"])*)"/g;
    var urlRE = new RegExp("^(https?://)" + escapeRegExp(domain) + "(/.*)$");

    var template = json.replace(stringRE, function (raw, content) {
        var urlMatch = urlRE.exec(content);
        if (!urlMatch) return raw; // no change, keep double-quotes
        return "`" + urlMatch[1] + "${serverUrl}" + urlMatch[2] + "`";
    });

    return template;
}

/**
 * Escapes any RegExp special characters.
 * Copied from https://stackoverflow.com/a/6969486/22364
 */
function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

【讨论】:

    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    • 2012-03-12
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多