Home  >  Article  >  Backend Development  >  Get nested key-value pairs of x-www-form-urlencoded request in JSON format in golang

Get nested key-value pairs of x-www-form-urlencoded request in JSON format in golang

王林
王林forward
2024-02-09 15:15:08421browse

Get nested key-value pairs of x-www-form-urlencoded request in JSON format in golang

In golang, when processing x-www-form-urlencoded requests in JSON format, you sometimes encounter nested key-value pairs. PHP editor Baicao provides a solution for everyone. By using the json.Unmarshal function to parse the request body into map[string]interface{} type, and then obtain the value of the nested key-value pair through type assertion and type conversion. This method is simple and effective and can help developers handle such requests easily. Next, we will introduce the specific implementation steps in detail.

Question content

I have a use case where we get the nested key value in the x-www-form-urlencoded body as shown below

name=abc&age=12&notes[key1]=value1&notes[key2]=value2

I tried url.parsequery("name=abc&age=12&notes\[key1\]=value1&notes\[key2\]=value2") but it gives

{
  "name": "abc",
  "age": 12,
  "notes[key1]": "value1",
  "notes[key2]": "value2"
}

How to get the value in the following json format for the above text

{
  "name": "abc",
  "age": 12,
  "notes": {
    "key1": "value1",
    "key2": "value2"
  }
}

Comments may be in 3-level nested format

I have tried url.parsequery and r.form but they both give notes[key1] and notes[key2].

Workaround

To unmarshal nested key values ​​using this type of query string parameter name, you can use derekstavis/go -qs This is the port of the rack query string parser.

This will return a map[string]interface{} with the following nested key values.

It is worth noting that the value of age is returned as a string, however, this is the same for url.parsequery. This package can be forked and modified if it needs to be marshaled into integers.

{
  "age": "12",
  "name": "abc",
  "notes": {
    "key1": "value1",
    "key2": "value2"
  }
}

A complete example is provided on the go playground, the code is as follows:

go playground URL: https://www.php.cn/link/0fc780bb04e74ce5ed154d2e49cfe2fd

package main

import (
    "encoding/json"
    "fmt"
    "log"

    qs "github.com/derekstavis/go-qs"
)

func main() {
    v := "name=abc&age=12&notes[key1]=value1&notes[key2]=value2"

    q, err := qs.Unmarshal(v)
    if err != nil {
        log.Fatal(err)
    }

    j, err := json.MarshalIndent(q, "", "  ")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(string(j))
}

The above is the detailed content of Get nested key-value pairs of x-www-form-urlencoded request in JSON format in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete