在Go语言中,可以使用encoding/json包来操作用户post的JSON数据。根据JSON数据格式不固定的特点,可以使用map[string]interface{}类型来解析和操作JSON数据。

下面是一个示例代码,演示如何解析和操作包含数组、字符串和其他类型的JSON数据:

package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"
)

func handleRequest(w http.ResponseWriter, r *http.Request) {
	// 解析JSON数据
	var data map[string]interface{}
	err := json.NewDecoder(r.Body).Decode(&data)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	// 操作JSON数据
	for key, value := range data {
		switch v := value.(type) {
		case string:
			fmt.Printf("Key: %s, Value: %s (string)\n", key, v)
		case []interface{}:
			fmt.Printf("Key: %s, Value: %v (array)\n", key, v)
		default:
			fmt.Printf("Key: %s, Value: %v\n", key, v)
		}
	}

	// 返回响应
	w.WriteHeader(http.StatusOK)
	w.Write([]byte("Success"))
}

func main() {
	http.HandleFunc("/", handleRequest)
	log.Fatal(http.ListenAndServe(":8080", nil))
}

在上面的示例中,handleRequest函数用于处理HTTP请求。首先,使用json.NewDecoder将请求体解析为map[string]interface{}类型的data变量。然后,使用switch语句根据值的类型进行不同的操作。如果值是字符串类型,则打印出字符串;如果值是数组类型,则打印出整个数组;否则,打印出其他类型的值。

你可以根据具体的需求对JSON数据进行进一步的操作,比如将其存储到数据库中或者进行其他业务逻辑处理。

golang 操作用户post的json数据 其中json数据格式包含数组 字符串等其他类型 json格式不固定

原文地址: https://www.cveoy.top/t/topic/hKIf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录