I'm trying to build a restful API and I'm struggling on how to serialize JSON data to a HTTP query string.

There are a number of mandatory and optional arguments that need to be passed in the request, e.g (represented as a JSON object below):

{
   "-columns" : [
      "name",
      "column"
   ],
   "-where" : {
      "-or" : {
         "customer_id" : 1,
         "services" : "schedule"
      }
   },
   "-limit" : 5,
   "return" : "table"
}

I need to support a various number of different clients so I'm looking for a standardized way to convert this json object to a query string. Is there one, and how does it look?

另一种 Select 是允许用户只传递消息体中的json对象,但我读到我应该避免这样做(HTTP GET with request body).

Any thoughts?

Edit for clarification:

Listing how some different languages encodes the given json object above:

  • 使用$.param:-columns[]=name&-columns[]=column&-where[-or][customer_id]=1&-where[-or][services]=schedule&-limit=5&return=column
  • 使用http_build_query:-columns[0]=name&-columns[1]=column&-where[-or][customer_id]=1&-where[-or][services]=schedule&-limit=5&return=column
  • Perl using URI::query_form: -columns=name&-columns=column&-where=HASH(0x59d6eb8)&-limit=5&return=column
  • Perl using complex_to_query: -columns:0=name&-columns:1=column&-limit=5&-where.-or.customer_id=1&-where.-or.services=schedule&return=column

jQuery and PHP is very similar. Perl using complex_to_query is also pretty similar to them. But none look exactly the same.

推荐答案

URL-encode (https://en.wikipedia.org/wiki/Percent-encoding) your JSON text and put it into a single query string parameter. for example, if you want to pass {"val": 1}:

mysite.com/path?json=%7B%22val%22%3A%201%7D

请注意,如果您的JSON太长,则会遇到URL长度限制问题.在这种情况下,我会将POST与正文一起使用(是的,我知道,当您想获取某些东西时发送POST不是"纯粹的",不太适合睡觉范例,但也不适合您的领域特定的基于JSONJSON的查询语言).

Json相关问答推荐

Google Page to JSON应用程序脚本出现CORS错误

如何在使用GO时检测JSON中不需要的字段?

我如何知道TJSONNumber是double还是double?

将数组中的值作为键连接到另一个数组中的值(Jolt)

无法从JSON解析ZonedDateTime,但可以使用格式化程序很好地解析

将PostgreSQL转换为JSON对象

数据到jsonObject到数据到 struct 是可能的吗?

如何使用Powershell查找所有包含特定键值对的JSON对象并迭代所有对象?

如何强制仅有一个元素的数组在JSON中生成方括号

将带有::text[]的JSON数组转换未按预期工作

使用不同行数的数据创建嵌套Jolt

使用杰克逊解析Kotlin 中的通用密封类

Kotlin Android Room 处理 Moshi TypeConverter 中的空对象列表

无法向 Json 数组添加新元素

JBuilder中未定义的局部变量或方法json

Python - 如何将 JSON 文件转换为数据框

Select 什么数据类型json或者jsonb或者text

jQuery JSON 响应总是触发 ParseError

Protocol Buffer vs Json - 何时 Select 一个而不是另一个

FastAPI:如何将正文读取为任何有效的 json?