如何将字典编码为HTTP GET查询字符串? [英] How should I encode dictionaries into HTTP GET query strings?

查看:138
本文介绍了如何将字典编码为HTTP GET查询字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HTTP GET查询字符串是键/值对的有序序列:

An HTTP GET query string is a ordered sequence of key/value pairs:

?spam=eggs&spam=ham&foo=bar

具有某些语义,等同于以下字典:

Is, with certain semantics, equivalent to the following dictionary:

{'spam': ['eggs', 'ham'], 'foo': bar}

对于请求的该页面的布尔属性,这恰好工作:

This happens to work well for boolean properties of that page being requested:

?expand=1&expand=2&highlight=7&highlight=9
{'expand': [1, 2], 'highlight': [7, 9]}

如果要停止扩展ID为2的元素,只需将其弹出expand值,然后再次对查询字符串进行urlencode.但是,如果您具有更多的模态属性(有3个以上的选择),则您确实想表示一个像这样的结构:

If you want to stop expanding the element with id 2, just pop it out of the expand value and urlencode the query string again. However, if you've got a more modal property (with 3+ choices), you really want to represent a structure like so:

{'highlight_mode': {7: 'blue', 9: 'yellow'}}

对应的id键的值是已知枚举的一部分.将其编码为查询字符串的最佳方法是什么?我正在考虑使用像这样的两个元组序列:

Where the values to the corresponding id keys are part of a known enumeration. What's the best way to encode this into a query string? I'm thinking of using a sequence of two-tuples like so:

?highlight_mode=(7,blue)&highlight_mode=(9,yellow)

也很高兴知道与约定相关的任何名称.我知道可能没有,但是能够使用名称而不是示例来谈论特定的东西真是太好了.谢谢!

It would also be nice to know any names that associate with the conventions. I know that there may not be any, but it's nice to be able to talk about something specific using a name instead of examples. Thanks!

推荐答案

通常的方法是这样:

highlight_mode[7]=blue&highlight_mode[9]=yellow

AFAIR,实际上有很多服务器端语言支持此功能,并且会为这些值生成一个漂亮的字典.

AFAIR, quite a few server-side languages actually support this out of the box and will produce a nice dictionary for these values.

这篇关于如何将字典编码为HTTP GET查询字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆