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

如何在客户端JavaScript中解析JSON API风格的查询参数?

解析JSON API风格的查询参数(客户端JavaScript实现)

下面是纯JS实现的解析函数,能处理你给出的嵌套filter格式,同时支持解析其他JSON API标准参数(比如sort、page等):

function parseJsonApiQueryParams(queryString) {
  // 处理查询字符串:去掉开头的?,过滤空项
  const params = queryString.replace(/^\?/, '').split('&').filter(item => item);
  const result = {};

  params.forEach(param => {
    // 拆分键和值,解码URI组件
    const [keyPart, value] = param.split('=').map(decodeURIComponent);
    // 解析嵌套键结构,比如filter[industries.id] -> ['filter', 'industries.id']
    const keys = keyPart.match(/([^\[\]]+)/g) || [];
    let current = result;

    keys.forEach((key, index) => {
      const isArrayIndex = /^\d+$/.test(key);
      // 最后一个键,直接赋值
      if (index === keys.length - 1) {
        if (isArrayIndex) {
          // 确保父级是数组
          if (!Array.isArray(current)) {
            const parentKey = keys[index - 1];
            current = [];
            result[parentKey] = current;
          }
          current[Number(key)] = value;
        } else {
          current[key] = value;
        }
      } else {
        // 初始化嵌套结构,根据下一个键判断是数组还是对象
        const nextKey = keys[index + 1];
        if (!current[key]) {
          current[key] = /^\d+$/.test(nextKey) ? [] : {};
        }
        current = current[key];
      }
    });
  });

  return result;
}

使用示例

假设你的URL是/search?filter[industries.id]=1&filter[locations.id]=3&filter[item_type][0]=temporary&sort=-created_at&page[number]=2,调用方式如下:

// 从当前URL获取查询字符串
const queryParams = parseJsonApiQueryParams(window.location.search);

// 检查filter是否存在
if (queryParams.filter) {
  console.log('Filter参数存在:', queryParams.filter);
  // 获取具体filter值
  console.log('industries.id:', queryParams.filter['industries.id']);
  console.log('locations.id:', queryParams.filter['locations.id']);
  console.log('item_type数组:', queryParams.filter.item_type); // 输出 ["temporary"]
}

// 解析其他JSON API参数
console.log('排序规则:', queryParams.sort); // 输出 "-created_at"
console.log('页码:', queryParams.page.number); // 输出 "2"

功能说明

  • 支持嵌套的filter结构,包括带点的对象键(比如industries.id)和数组索引(比如item_type[0])
  • 自动解码URI编码的参数值
  • 兼容sort、page、include等其他JSON API标准参数
  • 直接通过对象属性/键名访问对应值,判断参数是否存在只需检查对象是否有对应属性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 05:23:21