简体   繁体   English

React.js:将字符串转换为对象

[英]React.js: convert string to an object

I am using react to fetch Json data from an API, however, the API includes a key that has an object formatted as a String. 我正在使用react从API中获取Json数据,但是,该API包含一个键,该键的对象格式为String。 See example below: 请参见下面的示例:

 user_category:"employee",
 user_info:"{"user_id":"55","user_age":"27","user_company":"tesla"}"

To access the user-category, I simply use a header with an accessor , and the value displays on the table just fine, however I am having difficulties accessing the user_info key String using its keys and values using something like this: 要访问用户类别,我只需使用带有accessorheader ,并且该值在表中显示就可以了,但是我很难通过如下方式使用其键和值访问user_info键String:

 {
     Header: "User Id",
     accessor: "user_info.user_id"
   },
   {
     Header: "User Age",
     accessor: "user_info.user_age"
   },
   {
     Header: "User Company",
     accessor: "user_info.user_company"
   }

It's odd that the server is double-encoding the object to JSON like that (encoding the inner one and then encoding the whole thing). 奇怪的是,服务器会将对象双重编码为​​JSON(对内部对象进行编码,然后对整个对象进行编码)。

Ideally you'd have the server-side fixed, because what they're doing doesn't make sense, as JSON supports nested objects just fine. 理想情况下,您应该在服务器端进行修复,因为它们的操作没有意义,因为JSON支持嵌套对象就可以了。

If you have to solve the problem on the client, you'd use JSON.parse to turn the string into an object. 如果必须在客户端上解决问题,则可以使用JSON.parse将字符串转换为对象。

const atts = {
  user_category: "employee",
  user_info: "{"user_id":"55","user_age":"27","user_company":"tesla"}"
};

const userInfo = JSON.parse(atts.user_info);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM