gpt4 book ai didi

javascript - 将编码的 application/x-www-form-urlencoded post 数据转换为 json 对象

转载 作者:行者123 更新时间:2023-11-30 20:55:57 25 4
gpt4 key购买 nike

客户端希望能够使用默认内容类型 content-type:"application/x-www-form-urlencoded; charset=UTF-8"发出 xmlhttp ajax 请求,但以 API 的形式发送数据期望应用程序/json。所以请求是这样的:

  var settings = {
"async": true,
"crossDomain": true,
"url": "http://localhost:80/api/metadata/taxonomy",
"method": "POST",
"headers": {
"cache-control": "no-cache",
"postman-token": "62a245ad-a0a2-4dd3-bf84-37f622f00b7d"
},
"processData": false,
"data": "{\n\t\"practice\": [\"Learning\"]\n}"
}

$.ajax(settings).done(function (response) {
console.log(response);
});

但是 API 期望能够将 req.body 作为它可以立即使用的 JSON 对象获取:

"{"practice":["Learning"]}"

我可以将这个“{\n\t\"practice\": [\"Learning\"]\n}"转换成这个 "{"practice":["Learning"]}"在一些安全的/建议的方式? (没有一些自制的解析函数或正则表达式)

最佳答案

是的,JSON.parse 函数可用于此:

try{JSON.stringify(JSON.parse(data))}

将带有换行符的奇怪 json 转换为标准的一行字符串 json。

JSON.解析将json解析成对象

JSON.字符串化将一个对象转换为一行格式的 JSON 对象

尝试如果传递了无效的 json 字符串,JSON.parse 将失败。 (\ns 在 json.parse 中有效)

如果这意味着将 "{\n\"your\":\n\"object\"}" 转换为 javascript 对象,如 {"your": "object"},你可以只使用try{JSON.parse(variablename)}

根据 these answers , 对于较旧的浏览器,您可能需要 JSON-js

关于javascript - 将编码的 application/x-www-form-urlencoded post 数据转换为 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47660839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com