【问题标题】:what is correct Json conversion for string什么是正确的字符串 Json 转换
【发布时间】:2021-03-01 23:14:49
【问题描述】:

我有以下字符串,当我尝试将其转换为 JSON 时,如果给我一个错误

const banner =
" { "banners": [ { "startDate": "02/26/2021", "endDate": "12/25/2021","content": "Important changes have been made to the Visit google to review the updated document. <a href="https://www.google11.com" > Google11 </a>" } ] }" 

Href 出错,这是我用来转换的代码

const obj = JSON.parse( banner ? banner.replace(stripTag('div'), '') : banner ); 

【问题讨论】:

  • 您在 banner 声明中混淆了双引号。目前是语法错误
  • 你的代码毫无意义。当bannerfalsy 你要使用它吗?当它是truthy 时,您想以对我来说没有意义的方式对其进行字符串操作。即使使用div 字符串,stripTag 还能做什么?
  • 修复您的banner 声明,然后将其添加到JSON.parse。错误是什么?
  • 请检查我是否为我的字符串添加了图像

标签: javascript json angular


【解决方案1】:

我不确定你在问什么,但要解析你的字符串,你首先需要正确地转义它。为了简单起见,我在这里使用了反引号。

更新: 从您的编辑中,我现在可以看到您的字符串中有一个 div 标记,您需要清理它。这完全取决于该 div 最初是如何进入其中的,但如果它真的只是一个打开和关闭 div 标记,您可以在解析 JSON 之前简单地将其替换为字符串。

我认为您遇到的问题是:&lt;a href = "Any website link" &gt;Conditions&lt;/a&gt;。 要在字符串中转义,您必须使用 double \\,就像我在下面所做的那样,字符串将变为 &lt;a href = \\"Any website link\\" &gt;Conditions&lt;/a&gt;

const banner = `<div>{ "banners": [ { "startDate": "02/26/2021", "endDate": "12/25/2021", "content": "<span><strong>Important changes have been made to the Elastic Visit Terms and Conditions to review the updated document. <a href = \\"https://google11.com\\" >Conditions</a> </strong></span> " } ] }</div>`;
const cleanBanner = banner.replace('<div>','').replace('</div>','');
const parsed = JSON.parse(cleanBanner);

console.log(parsed)

【讨论】:

  • 我刚刚用正确的 URL 字符串再次更新了我的字符串,请再次检查
  • 你的“字符串”还是坏了。它没有正确逃脱。它会出错,因为它不是有效的 javascript...
  • 是的,字符串中的问题是什么我怎样才能使它适用于 Json?
  • 我在答案中向您展示了。字符串的所有元素都必须在引号内...
  • 请检查一下我已经添加了我的字符串的图像
【解决方案2】:

如果“要解析的字符串”在您的源代码中是一个常量字符串,那么它必然会由您的语言处理。那么,为什么不“打印它”呢?字符串值是否等于您的预期?是的,可能不会。

【讨论】:

  • 如何 Paser -- Href="www" -- Json 中的值?
  • { "banners": [ { "startDate": "02/26/2021", "endDate": "12/25/2021", "content": " 已对访问条款和条件进行了重要更改,以查看更新后的文档。条件 " } ] }
  • 这是我的链接,我想把它转换成 JSON
猜你喜欢
  • 1970-01-01
  • 2019-09-13
  • 1970-01-01
  • 2014-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-27
  • 2012-03-08
相关资源
最近更新 更多