【问题标题】:convert sting (object of object) in object [duplicate]在对象中转换字符串(对象的对象)[重复]
【发布时间】:2021-10-20 04:13:21
【问题描述】:

我在字符串中有一个 API 响应

"{"div":{"display": "flex","flexDirection": "column","alignItems":"center","fontFamily":"Helvetica Neue"},"a":{"fontSize": 16, "textAlign": "center","fontWeight":"bold","color":"#324F85"},"p":{"fontSize": 34,"textAlign":"center","color": "#7f8f96d"},"h5": {"fontWeight": "normal","fontSize": 18,"textAlign":"center"}}"

我想把字符串转换成对象

{div:{display: 'flex',flexDirection: 'column',alignItems: 'center',fontFamily:'Helvetica Neue'},a: {fontSize: 16,textAlign: 'center',fontWeight: 'bold',color: '#324F85'}, p:{fontSize: 34,textAlign: 'center',color: '#7f8f96d6'},h5: { fontWeight: 'normal',fontSize: 18,textAlign: 'center'}}

【问题讨论】:

  • 这能回答你的问题吗? Converting a string to JSON object
  • @Kordrad 不完全适用,因为 OP 的 JSON 无效。
  • @VLAZ 为什么它无效?
  • JSON 要求键和字符串值用双引号括起来。您的数据使用单引号。
  • @VLAZ 我已经更新了问题(双引号中的数据)仍然给出错误:意外的标识符

标签: javascript css json api


【解决方案1】:

这可以通过JSON.parse() 函数来完成,如下所示:

const apiResponseAsObject = JSON.parse(apiResponseAsString)

对于以后的问题,请将您的代码格式化为实际代码。

【讨论】:

  • 这不起作用,因为 OP 的字符串不是有效的 JSON。
  • 感谢重播,我已经尝试过了,但它不起作用,错误:位置 1 处的 JSON 中的 Unexpected '
猜你喜欢
  • 2014-08-20
  • 2023-03-11
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-25
  • 2020-11-15
相关资源
最近更新 更多