登录
首页 >  Golang >  Go问答

处理包含单引号的 JSON 键

来源:stackoverflow

时间:2024-02-07 10:03:23 361浏览 收藏

从现在开始,努力学习吧!本文《处理包含单引号的 JSON 键》主要讲解了等等相关知识点,我会在golang学习网中持续更新相关的系列文章,欢迎大家关注并积极留言建议。下面就先一起来看一下本篇正文内容吧,希望能帮到你!

问题内容

对此我感到很困惑。 我需要加载一些以 json 序列化的数据(来自法国数据库),其中某些键带有单引号。

这是一个简化版本:

package main

import (
    "encoding/json"
    "fmt"
)

type product struct {
    name string `json:"nom"`
    cost int64  `json:"prix d'achat"`
}

func main() {
    var p product
    err := json.unmarshal([]byte(`{"nom":"savon", "prix d'achat": 170}`), &p)
    fmt.printf("product cost: %d\nerror: %s\n", p.cost, err)
}

// product cost: 0
// error: %!s()

解组不会导致错误,但“prix d'achat”(p.cost) 未正确解析。

当我解组到 map[string]any 时,“prix d'achat”密钥按照我的预期进行解析:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    blob := map[string]any{}
    err := json.Unmarshal([]byte(`{"nom":"savon", "prix d'achat": 170}`), &blob)
    fmt.Printf("blob: %f\nerror: %s\n", blob["prix d'achat"], err)
}

// blob: 170.000000
// error: %!s()

我检查了有关结构标记的 json.marshal 文档,但找不到我正在尝试处理的数据的任何问题。

我在这里遗漏了一些明显的东西吗? 如何使用结构标签解析包含单引号的 json 键?

非常感谢您的见解!


正确答案


我在文档中没有找到任何内容,但是json 编码器将单引号视为标记名称中的保留字符

func isvalidtag(s string) bool {
    if s == "" {
        return false
    }
    for _, c := range s {
        switch {
        case strings.containsrune("!#$%&()*+-./:;<=>?@[]^_{|}~ ", c):
            // backslash and quote chars are reserved, but
            // otherwise any punctuation chars are allowed
            // in a tag name.
        case !unicode.isletter(c) && !unicode.isdigit(c):
            return false
        }
    }
    return true
}

我认为在这里提出问题是合理的。与此同时,您将必须实现 json.unmarshaler 和/或json.marshaler。这是一个开始:

func (p *Product) UnmarshalJSON(b []byte) error {
    type product Product // revent recursion
    var _p product

    if err := json.Unmarshal(b, &_p); err != nil {
        return err
    }

    *p = Product(_p)

    return unmarshalFieldsWithSingleQuotes(p, b)
}

func unmarshalFieldsWithSingleQuotes(dest interface{}, b []byte) error {
    // Look through the JSON tags. If there is one containing single quotes,
    // unmarshal b again, into a map this time. Then unmarshal the value
    // at the map key corresponding to the tag, if any.
    var m map[string]json.RawMessage

    t := reflect.TypeOf(dest).Elem()
    v := reflect.ValueOf(dest).Elem()

    for i := 0; i < t.NumField(); i++ {
        tag := t.Field(i).Tag.Get("json")
        if !strings.Contains(tag, "'") {
            continue
        }

        if m == nil {
            if err := json.Unmarshal(b, &m); err != nil {
                return err
            }
        }

        if j, ok := m[tag]; ok {
            if err := json.Unmarshal(j, v.Field(i).Addr().Interface()); err != nil {
                return err
            }
        }
    }

    return nil
}

在操场上尝试一下:https://go.dev/play/p/aupacxorjoo一个>

理论要掌握,实操不能落!以上关于《处理包含单引号的 JSON 键》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>