卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章35655本站已运行398

从包含单引号的 JSON 键解组

从包含单引号的 json 键解组

php小编新一介绍了一种有趣的技巧,即从包含单引号的JSON键解组。这个技巧可以帮助开发人员在处理JSON数据时更加灵活,避免因为包含单引号而导致的解析错误。通过使用一些简单的技巧和函数,开发人员可以轻松地处理这种情况,确保JSON数据的正确解析和处理。这个技巧对于那些经常处理JSON数据的开发人员来说是非常有用的,能够提高开发效率和代码质量。

问题内容

对此我感到很困惑。 我需要加载一些以 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: %dnerror: %sn", p.cost, err)
}

// product cost: 0
// error: %!s(<nil>)

解组不会导致错误,但“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: %fnerror: %sn", blob["prix d'achat"], err)
}

// blob: 170.000000
// error: %!s(<nil>)

我检查了有关结构标记的 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://www.php.cn/link/9b47b8678d84ea8a0f9fe6c4ec599918一个>

卓越飞翔博客
上一篇: 为什么 http post 请求在 go 中给我带来很高的内存使用率?
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏