我有此正文请求需要处理:
{
"event" : "message",
"token" : "957fa13859e06b22b96060ab97df934e5aec0ca02c432",
"uid" : "",
"contact[uid]" : "",
"contact[name]" : "",
"contact[type]": "user",
"message[dtm]": "1530022083",
"message[uid]": "87FA901709E3C05CCB0270B6B3C893AF",
"message[cuid]": "",
"message[dir]" : "i",
"message[type]" : "chat",
"message[body][text]" : "",
"message[ack]": "3"
}
如何用[]读取属性?当它转换为json objetc时,带有[]的属性是一个字符串,如下所示:
{ event: 'message',
token: '957fa13859e06b22b96060ab97df934e5aec0ca02c432',
uid: '',
'contact[uid]': '',
'contact[name]': '',
'contact[type]': 'user',
'message[dtm]': '1530022083',
'message[uid]': '87FA901709E3C05CCB0270B6B3C893AF',
'message[cuid]': '',
'message[dir]': 'i',
'message[type]': 'chat',
'message[body][text]': '',
'message[ack]': '3' }
任何想法如何获取数据?
亲切的问候
答案 0 :(得分:0)
我知道这里发生了什么
您已经使用了将查询字符串转换为JSON的函数,但您使用的函数仅适用于平面查询字符串(无嵌套变量)。
由于您正在使用Node.JS,因此应尝试NPM Package qs
它需要这样的查询字符串:
event=message&token=957fa13859e06b22b96060ab97df934e5aec0ca02c432&uid=&contact[uid]=&contact[name]=&contact[type]=user&message[dtm]=1530022083&message[uid]=87FA901709E3C05CCB0270B6B3C893AF&message[cuid]=&message[dir]=i&message[type]=chat&message[body][text]=&message[ack]=3
并创建一个像这样的JSON对象:
{
event: 'message',
token: '957fa13859e06b22b96060ab97df934e5aec0ca02c432',
uid: '',
contact: { uid: '', name: '', type: 'user' },
message: {
dtm: '1530022083',
uid: '87FA901709E3C05CCB0270B6B3C893AF',
cuid: '',
dir: 'i',
type: 'chat',
body: {
text: ''
},
ack: '3'
}
}
仅包含以下代码:
const qs = require("qs");
let querystring = "event=message&token=957fa13859e06b22b96060ab97df934e5aec0ca02c432&uid=&contact[uid]=&contact[name]=&contact[type]=user&message[dtm]=1530022083&message[uid]=87FA901709E3C05CCB0270B6B3C893AF&message[cuid]=&message[dir]=i&message[type]=chat&message[body][text]=&message[ack]=3";
let JSONquery = qs.parse(querystring);
console.log(JSONquery);
希望有帮助。