react-native fetch api响应解析为特定格式

时间:2018-02-24 07:40:28

标签: react-native fetch fetch-api

以下是我从API获取响应的代码 -

fetch('http://34.215.9.246:9000/api/chat/get-chat-messages-for-participant?participantId='+this.state.participantId+'&projectId='+this.state.projectId)
        .then((response) => response.json())
        .then((responseJson) => {
          console.log(responseJson)
          var reponseApi=responseJson.stringify; 
          console.log(reponseApi)
         // console.log((responseJson.stringify.replace("\"customizedChatmessage\": \"",'')).replace("\"",""));
          this._isMounted = true;
          this.setState(() => {
            return {
              messages: require('../../assets/data/messages.js'),
              //messages: (responseJson.replace("\"customizedChatmessage\": \"",'')).replace("\"","")
            };
          });
        })
        .catch((error) => {
          console.error(error);
        });

这个api的反应是:

[ {
    "customizedChatmessage": "{_id: Math.round(Math.random() * 1000000), text: HI,user: {_id: 5a91138ce4b01f2df36531a5, name: alok sharama sir}, },"
  },
  {
    "customizedChatmessage": "{_id: Math.round(Math.random() * 1000000), text: Hello World,user: {_id: 5a91138ce4b01f2df36531a5, name: alok sharama sir}, },"
  },
  {
    "customizedChatmessage": "{_id: Math.round(Math.random() * 1000000), text: test message,user: {_id: 5a91138ce4b01f2df36531a5, name: alok sharama sir}, },"
  }
]

我想将响应修改为特定格式,如下所示:

[{
      _id: 516152, text: 'Hi',user: {_id: 1, name: 'Alok Sharma'},
    },
    {
      _id: 396263, text: 'how r u ',user: {_id: 1, name: 'Alok Sharma'}, 
    },
    {
      _id: 652380, text: 'image is not fine. cahnge it',user: {_id: 1, name: 'Alok Sharma'}, 
    },
    {
      _id: 186058, text: 'image is not fine. cahnge it',user: {_id: 1, name: 'Alok Sharma'}, 
    },
    {
      _id: 104931, text: 'image is not fine. cahnge it',user: {_id: 1, name: 'Alok Sharma'}, 
    }]

帮我解决这个问题。感谢

0 个答案:

没有答案