从包含单引号的 JSON 键解组

2024年 2月 14日 57.1k 0

从包含单引号的 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()

登录后复制

解组不会导致错误,但“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()

登录后复制

我检查了有关结构标记的 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 登录后复制

在操场上尝试一下:https://www.php.cn/link/9b47b8678d84ea8a0f9fe6c4ec599918一个>

以上就是从包含单引号的 JSON 键解组的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论