【问题标题】:Dynamically update String using JSON object values in JS在 JS 中使用 JSON 对象值动态更新 String
【发布时间】:2020-05-14 21:54:30
【问题描述】:

我有这个函数来创建它发出请求的位置,存储数据。 (存储为 OBJ)

发出第二个请求以获取要调用的新 URL。此 URL 要求我更新 url 以包含存储数据中的值。

正在保存的数据:

{
  "location": {
    "ip": "78.152.221.20",
    "success": true,
    "type": "IPv4",
    "continent": "Europe",
    "continent_code": "EU",
    "country": "Ireland",
    "country_code": "IE",
    "country_flag": "https://cdn.ipwhois.io/flags/ie.svg",
    "country_capital": "Dublin",
    "country_phone": "+353",
    "country_neighbours": "GB",
    "region": "County Dublin",
    "city": "Swords",
    "latitude": "53.4557467",
    "longitude": "-6.2197406",
    "asn": "AS15502",
    "org": "Vodafone Ireland",
    "isp": "Vodafone Ireland Limited",
    "timezone": "Europe/Dublin",
    "timezone_name": "Greenwich Mean Time",
    "timezone_dstOffset": "0",
    "timezone_gmtOffset": "0",
    "timezone_gmt": "GMT 0:00",
    "currency": "Euro",
    "currency_code": "EUR",
    "currency_symbol": "€",
    "currency_rates": "0.926884",
    "currency_plural": "euros",
    "completed_requests": 49
  }
}

第二个请求返回这个我需要更新的 URL:

"url": "https://api.sunrise-sunset.org/json?lat={{ location.latitude }}&lng={{ location.longitude }}"

我试图创建一个操作字符串并返回的函数。一旦返回,它将被设置一个字符串模板文字,如下所示:

`https://api.sunrise-sunset.org/json?lat=${OBJ['location']['latitude']&lng=${OBJ['location']['longitude']`

但它不起作用,它只是使用字符串,而不是将先前存储的值作为 OBJ。

这是我的代码,任何建议或指针或任何东西都将不胜感激。

const interpolateURLorMessage = (string) => {
  if (CONST.DEBUG) {
    console.log('functions.checkURLorMessage: string:', string);
  }

  if (!string) {
    return null;
  }

  if (string.includes('{{') && string.includes('}}')) {
    const myRegexp = /\{{(.*?)\}}/g;
    const matches = string.match(myRegexp);

    let newURL = `${string}`;
    matches.forEach((ele) => {
      const match = ele;
      let newMatch = ele.replace('.', '\'][\'');
      newMatch = newMatch.replace('{{', '${OBJ[\'');
      newMatch = newMatch.replace('}}', '\']');
      newMatch = newMatch.replace(/\s/g, '');
      newURL = newURL.replace(match, newMatch);
    });

    return newURL;
  } else {
    // Noting to interpolate
    return string;
  }
};

【问题讨论】:

  • 您不想使用车把之类的东西吗?那将为您完成工作...
  • 你可以做const parsedURL = Handlebars.compile(url)(locationObj);
  • 请注意,模板文字本质上是 Javascript,是字符串与表达式连接的语法糖,因此您无法在运行时修改它们。那将是自修改代码或类似执行 eval。

标签: javascript json npm ecmascript-6 string-literals


【解决方案1】:

在正则表达式上使用替换函数并使用 split(.) 假设括号中的值是属性值的简单实现。如果它需要更复杂,您可能可以使用类似于 eval 或更复杂的解析的东西。我相信 lodash 有一些属性路径访问功能,所以你不必重新发明它。
Mustache 模板也可能是一种选择,您可以预编译它们以避免开销。

但这适用于您那里的简单用例。

var OBJ={};CONST={DEBUG:true};

const interpolateURLorMessage = (string) => {
  if (CONST.DEBUG) {
    console.log('functions.checkURLorMessage: string:', string);
  }

  if (!string) {
    return null;
  }

  if (string.includes('{{') && string.includes('}}')) {
    return string.replace(/\{{(.*?)\}}/g,(r,p1)=>p1.trim().split('.').reduce((acc,p)=>acc[p],OBJ));
  } else {
    // Noting to interpolate
    return string;
  }
};

var urlobj = {"url": "https://api.sunrise-sunset.org/json?lat={{ location.latitude }}&lng={{ location.longitude }}"};

var data = {
  "location": {
    "ip": "78.152.221.20",
    "success": true,
    "type": "IPv4",
    "continent": "Europe",
    "continent_code": "EU",
    "country": "Ireland",
    "country_code": "IE",
    "country_flag": "https://cdn.ipwhois.io/flags/ie.svg",
    "country_capital": "Dublin",
    "country_phone": "+353",
    "country_neighbours": "GB",
    "region": "County Dublin",
    "city": "Swords",
    "latitude": "53.4557467",
    "longitude": "-6.2197406",
    "asn": "AS15502",
    "org": "Vodafone Ireland",
    "isp": "Vodafone Ireland Limited",
    "timezone": "Europe/Dublin",
    "timezone_name": "Greenwich Mean Time",
    "timezone_dstOffset": "0",
    "timezone_gmtOffset": "0",
    "timezone_gmt": "GMT 0:00",
    "currency": "Euro",
    "currency_code": "EUR",
    "currency_symbol": "€",
    "currency_rates": "0.926884",
    "currency_plural": "euros",
    "completed_requests": 49
  }
};

OBJ=data;
console.log(
interpolateURLorMessage(urlobj.url)
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-27
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 2020-04-19
    • 1970-01-01
    相关资源
    最近更新 更多