admin管理员组

文章数量:1323335

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. See example below:

 user_category:"employee",
 user_info:"{"user_id":"55","user_age":"27","user_pany":"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:

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

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. See example below:

 user_category:"employee",
 user_info:"{"user_id":"55","user_age":"27","user_pany":"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:

 {
     Header: "User Id",
     accessor: "user_info.user_id"
   },
   {
     Header: "User Age",
     accessor: "user_info.user_age"
   },
   {
     Header: "User Company",
     accessor: "user_info.user_pany"
   }
Share Improve this question asked Jun 4, 2019 at 1:09 ZeusoxZeusox 8,47810 gold badges36 silver badges64 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 3

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).

Ideally you’d have the server-side fixed, because what they’re doing doesn’t make sense, as JSON supports nested objects just fine.

If you have to solve the problem on the client, you’d use JSON.parse to turn the string into an object.

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

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

本文标签: javascriptReactjs convert string to an objectStack Overflow