You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript解析x-www-form-urlencoded格式字符串?

嘿,我来帮你搞定这个问题!先得明确两种可能的场景——毕竟你提到响应是application/x-www-form-urlencoded格式,但给出的responseText看起来是标准JSON,咱们一个个说:

场景1:响应内容是标准的application/x-www-form-urlencoded键值对

如果你的响应体实际是类似response[header][error_code]=0&response[body][foo]=foobar&response[body][date]=2018-04-27这种用&分隔的键值对格式,那用浏览器原生的URLSearchParams就能轻松解析,要是想转成你给出的嵌套JSON结构,还得做一点额外处理:

// 假设这是你的原始urlencoded响应文本
const urlEncodedStr = 'response[header][error_code]=0&response[body][foo]=foobar&response[body][date]=2018-04-27';
const params = new URLSearchParams(urlEncodedStr);

// 把扁平的键值对转成嵌套JSON对象
const parsedResult = {};
for (const [key, value] of params) {
  // 拆分嵌套的键名,比如把response[header][error_code]拆成["response", "header", "error_code"]
  const keySegments = key.replace(/\]/g, '').split('[');
  let currentLevel = parsedResult;
  
  keySegments.forEach((segment, index) => {
    if (index === keySegments.length - 1) {
      // 最后一段直接赋值,数字类型可以手动转换
      currentLevel[segment] = isNaN(+value) ? value : +value;
    } else {
      // 非最后一段就创建嵌套对象
      currentLevel[segment] = currentLevel[segment] || {};
      currentLevel = currentLevel[segment];
    }
  });
}

console.log(parsedResult);
// 输出就是你要的结构:
// { response: { header: { error_code: 0 }, body: { foo: 'foobar', date: '2018-04-27' } } }
场景2:响应头标了application/x-www-form-urlencoded但内容是JSON字符串

从你给出的responseText来看,它本身就是一个合法的JSON字符串:

{ "response": { "header": { "error_code": 0 }, "body": { "foo": "foobar", "date": "2018-04-27" } } }

这种情况下,不管响应头的类型是什么,直接用JSON.parse()解析就行,之后就能正常用Object.keys()遍历键了:

const responseText = '{ "response": { "header": { "error_code": 0 }, "body": { "foo": "foobar", "date": "2018-04-27" } } }';
const parsedData = JSON.parse(responseText);

// 举个例子,遍历body里的所有键
Object.keys(parsedData.response.body).forEach(key => {
  console.log(`${key}: ${parsedData.response.body[key]}`);
});
// 输出:
// foo: foobar
// date: 2018-04-27

要是你的响应是把JSON包在urlencoded参数里(比如格式是json={"response": {...}}),那可以先提取出JSON部分再解析:

const params = new URLSearchParams(responseText);
const jsonStr = params.get('json');
const parsedData = JSON.parse(jsonStr);

内容的提问来源于stack exchange,提问作者Moegamat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:58:23