使用 JavaScript 解析 JSON API 查询中的参数/值

问题描述 投票:0回答:1

如何在 JavaScript 中解析 JSON API 样式查询?一个示例查询是:

/search?filter[industries.id]=1&filter[locations.id]=3&filter[item_type][0]=temporary

我想提取过滤器字段和值(最好是其他 JSON API 参数)。我不太介意结果是什么格式,无论是对象还是数组等。我需要能够检查过滤器是否存在并获取它的值。

这是客户端,而不是服务器。

很高兴使用图书馆,因为有一个图书馆,但找不到一个。

javascript json json-api
1个回答
0
投票

处理此类请求的最简单、最明显的方法是将其转换为 JSON,如下所示:

{
 "industries.id": 1, 
 "locations.id": 3, 
 "item_type": ["temporary"]
}

这是执行此操作的代码示例


    const params = new URLSearchParams("filter[industries.id]=1&filter[locations.id]=3&filter[item_type][0]=temporary");


    const result = {};

    for (const [key, value] of params) {
        // Remove 'filter[' prefix and ']' suffix, then split by '][' for nested properties
        const path = key.replace(/^filter\[|\]$/g, '').split('][');
        // ...
        // Handle value here. Parse numbers, strings, arrays etc
        // ...
        result[path[0]] = parsedValue
    }
        
© www.soinside.com 2019 - 2024. All rights reserved.