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: %d\nerror: %s\n", 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: %f\nerror: %s\n", 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一个>
以上是从包含单引号的 JSON 键解组的详细内容。更多信息请关注PHP中文网其他相关文章!

Gooffersrobustfeaturesforsecurecoding,butdevelopersmustimplementsecuritybestpracticeseffectively.1)UseGo'scryptopackageforsecuredatahandling.2)Manageconcurrencywithsynchronizationprimitivestopreventraceconditions.3)SanitizeexternalinputstoavoidSQLinj

Go的错误接口定义为typeerrorinterface{Error()string},允许任何实现Error()方法的类型被视为错误。使用步骤如下:1.基本检查和记录错误,例如iferr!=nil{log.Printf("Anerroroccurred:%v",err)return}。2.创建自定义错误类型以提供更多信息,如typeMyErrorstruct{MsgstringDetailstring}。3.使用错误包装(自Go1.13起)来添加上下文而不丢失原始错误信息,

对效率的Handleerrorsinconcurrentgopragrs,UsechannelstocommunicateErrors,EmparterRorwatchers,InsterTimeouts,UsebufferedChannels和Provideclearrormessages.1)USEchannelelStopassErstopassErrorsErtopassErrorsErrorsFromGoroutInestotheStothemainfunction.2)

在Go语言中,接口的实现是通过隐式的方式进行的。1)隐式实现:类型只要包含接口定义的所有方法,就自动满足该接口。2)空接口:interface{}类型所有类型都实现,适度使用可避免类型安全问题。3)接口隔离:设计小而专注的接口,提高代码的可维护性和重用性。4)测试:接口有助于通过模拟依赖进行单元测试。5)错误处理:通过接口可以统一处理错误。

go'sinterfacesareimpliclyimplysed,与Javaandc#wheRequireexplitiCimplation.1)Ingo,AnyTypewithTheRequiredMethodSautSautsautautapitymethodimimplementalyimimplementsaninternItherninternionterface,callingingSimplicity andficityity.2)

Toensureinitfunctionsareeffectiveandmaintainable:1)Minimizesideeffectsbyreturningvaluesinsteadofmodifyingglobalstate,2)Ensureidempotencytohandlemultiplecallssafely,and3)Breakdowncomplexinitializationintosmaller,focusedfunctionstoenhancemodularityandm

goisidealforbeginnersandsubableforforcloudnetworkservicesduetoitssimplicity,效率和concurrencyFeatures.1)installgromtheofficialwebsitealwebsiteandverifywith'.2)

开发者应遵循以下最佳实践:1.谨慎管理goroutines以防止资源泄漏;2.使用通道进行同步,但避免过度使用;3.在并发程序中显式处理错误;4.了解GOMAXPROCS以优化性能。这些实践对于高效和稳健的软件开发至关重要,因为它们确保了资源的有效管理、同步的正确实现、错误的适当处理以及性能的优化,从而提升软件的效率和可维护性。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

WebStorm Mac版
好用的JavaScript开发工具

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具