简体   繁体   English

将 Req.query 字符串格式化为 JavaScript Object

[英]Format a Req.query string to JavaScript Object

I have a req.query from a get request我有一个来自 get 请求的 req.query

get <host>/api/tree/path-search?tree="{1:{2:{4:null,5:null},3:null}}"

How i convert it to this form in javaScript我如何在 javaScript 中将其转换为这种形式

const obj = { 1 : { 2 : { 4 : null, 5 : null },3 : null}};

is the const obj a JavaScript Object是 const obj 是 JavaScript Object

I'd strongly suggest changing what you put in tree to JSON so you can use the built-in JSON parser ( JSON.parse ).强烈建议将您放入tree中的内容更改为JSON以便您可以使用内置的 JSON 解析器( JSON.parse )。 The URI might look like this: URI 可能如下所示:

get <host>/api/tree/path-search?tree=%7B%221%22%3A%7B%222%22%3A%7B%224%22%3Anull%2C%225%22%3Anull%7D%2C%223%22%3Anull%7D%7D

...where that value for tree is the URI-encoded version of ...其中tree的值是 URI 编码的版本

{"1":{"2":{"4":null,"5":null},"3":null}}

Which is valid JSON that parses to what you want.哪个是有效的 JSON 可以解析为您想要的。


What you have now is a valid JavaScript object literal, but not valid JSON.您现在拥有的是有效的 JavaScript object 文字,但不是有效的 JSON。 That means you could evaluate it with something that evaluates (executes) JavaScript code like eval or new Function , but that executes arbitrary code , which you don't want to do on a server .这意味着您可以使用可以评估(执行)JavaScript 代码(例如evalnew Function )的东西来评估它,但这会执行您不想在服务器上执行的任意代码

Alternatively, parse it with a JavaScript parser.或者,使用 JavaScript 解析器对其进行解析。 There are several available for the Node.js environment.有几个可用于 Node.js 环境。 Then you'd walk through the resulting AST tree building the described object.然后,您将遍历生成的 AST 树,构建所描述的 object。 Which is obviously a pain, which is why I'd use JSON.这显然是一种痛苦,这就是我使用 JSON 的原因。 :-) :-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM