"{"status":1,"programUrl":"","lastCommand":"1647860970304884737\/1654313899182313473\/multifunctionCard\/invoke"}" 这样一个这样一个string类型的数据,转化为{ messageId: string, // 对应ask的id timestamp: string, functionKey: string, // 对应ask code: int, // 执行结果,0为成功,若为非0时,data直接为失败描述,例如 { ..., code: -1, data: "未知异常" } data: string // 根据code与functionKey决定 }这样格式的,js代码
时间: 2023-07-07 21:27:16 浏览: 34
可以使用以下代码将给定的字符串转换为所需的格式:
```javascript
const str = '{"status":1,"programUrl":"","lastCommand":"1647860970304884737\/1654313899182313473\/multifunctionCard\/invoke"}';
const obj = JSON.parse(str);
const messageId = obj.lastCommand.split('/')[0];
const timestamp = obj.lastCommand.split('/')[1];
const functionKey = obj.lastCommand.split('/')[2];
const code = obj.status === 1 ? 0 : -1;
const data = obj.status === 1 ? JSON.stringify({ programUrl: obj.programUrl }) : obj.programUrl;
const result = {
messageId,
timestamp,
functionKey,
code,
data,
};
console.log(result);
```
这段代码首先将给定的字符串解析为一个JavaScript对象。然后,从`lastCommand`属性中提取`messageId`、`timestamp`和`functionKey`。接下来,根据`status`属性的值确定`code`和`data`的值,最后将所有值存储到一个新对象中并输出。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)