iter.json: Go에서 JSON을 반복하고 조작하는 강력하고 효율적인 방법
Go에서 구조화되지 않은 JSON 데이터를 수정해야 했던 적이 있나요? 어쩌면 블랙리스트에 있는 모든 필드를 삭제하거나, 키 이름을 camelCase에서 snake_case로 바꾸거나, JavaScript가 int64를 좋아하지 않기 때문에 모든 숫자 ID를 문자열로 변환해야 했을 수도 있습니다. 귀하의 솔루션이 인코딩/json을 사용하여 모든 것을 map[string]any로 비정렬화한 다음 다시 마샬링하는 것이라면... 솔직히 말해서 그것은 효율적이지 않습니다!
JSON 데이터를 반복하면서 각 항목의 경로를 파악하고 즉시 해당 항목으로 무엇을 할지 정확하게 결정할 수 있다면 어떨까요?
그렇습니다! 좋은 소식이 있어요! Go 1.23의 새로운 반복자 기능을 사용하면 JSON을 반복하고 조작하는 더 나은 방법이 있습니다. Go에서 JSON 작업을 위한 강력하고 효율적인 동반자인 ezpkg.io/iter.json을 만나보세요.
1. JSON 반복
alice.json 파일이 있다고 가정:
{ "name": "Alice", "age": 24, "scores": [9, 10, 8], "address": { "city": "The Sun", "zip": 10101 } }
먼저 for range Parse()를 사용하여 JSON 파일을 반복한 다음 각 항목의 경로, 키, 토큰 및 레벨을 인쇄해 보겠습니다. 예제/01.iter를 참조하세요.
package main import ( "fmt" "ezpkg.io/errorz" iterjson "ezpkg.io/iter.json" ) func main() { data := `{"name": "Alice", "age": 24, "scores": [9, 10, 8], "address": {"city": "The Sun", "zip": 10101}}` // ?Example: iterate over json fmt.Printf("| %12v | %10v | %10v |%v|\n", "PATH", "KEY", "TOKEN", "LVL") fmt.Println("| ------------ | ---------- | ---------- | - |") for item, err := range iterjson.Parse([]byte(data)) { errorz.MustZ(err) fmt.Printf("| %12v | %10v | %10v | %v |\n", item.GetPathString(), item.Key, item.Token, item.Level) } }
코드는 다음을 출력합니다:
| PATH | KEY | TOKEN |LVL| | ------------ | ---------- | ---------- | - | | | | { | 0 | | name | "name" | "Alice" | 1 | | age | "age" | 24 | 1 | | scores | "scores" | [ | 1 | | scores.0 | | 9 | 2 | | scores.1 | | 10 | 2 | | scores.2 | | 8 | 2 | | scores | | ] | 1 | | address | "address" | { | 1 | | address.city | "city" | "The Sun" | 2 | | address.zip | "zip" | 10101 | 2 | | address | | } | 1 | | | | } | 0 |
2. JSON 구축
Builder를 사용하여 JSON 데이터를 구축하세요. 들여쓰기에 대한 선택적 인수를 허용합니다. 예제/02.builder를 참조하세요.
b := iterjson.NewBuilder("", " ") // open an object b.Add("", iterjson.TokenObjectOpen) // add a few fields b.Add("name", "Alice") b.Add("age", 22) b.Add("email", "alice@example.com") b.Add("phone", "(+84) 123-456-789") // open an array b.Add("languages", iterjson.TokenArrayOpen) b.Add("", "English") b.Add("", "Vietnamese") b.Add("", iterjson.TokenArrayClose) // close the array // accept any type that can marshal to json b.Add("address", Address{ HouseNumber: 42, Street: "Ly Thuong Kiet", City: "Ha Noi", Country: "Vietnam", }) // accept []byte as raw json b.Add("pets", []byte(`[{"type":"cat","name":"Kitty","age":2},{"type":"dog","name":"Yummy","age":3}]`)) // close the object b.Add("", iterjson.TokenObjectClose) out := errorz.Must(b.Bytes()) fmt.Printf("\n--- build json ---\n%s\n", out)
들여쓰기를 사용하여 JSON을 출력합니다.
{ "name": "Alice", "age": 22, "email": "alice@example.com", "phone": "(+84) 123-456-789", "languages": [ "English", "Vietnamese" ], "address": {"house_number":42,"street":"Ly Thuong Kiet","city":"Ha Noi","country":"Vietnam"}, "pets": [ { "type": "cat", "name": "Kitty", "age": 2 }, { "type": "dog", "name": "Yummy", "age": 3 } ] }
3. JSON 형식 지정
해당 키와 값을 빌더에 보내 JSON 데이터를 재구성하거나 형식을 지정할 수 있습니다. 예제/03.reformat을 참조하세요.
{ // ?Example: minify json b := iterjson.NewBuilder("", "") for item, err := range iterjson.Parse(data) { errorz.MustZ(err) b.AddRaw(item.Key, item.Token) } out := errorz.Must(b.Bytes()) fmt.Printf("\n--- minify ---\n%s\n----------\n", out) } { // ?Example: format json b := iterjson.NewBuilder("? ", "\t") for item, err := range iterjson.Parse(data) { errorz.MustZ(err) b.AddRaw(item.Key, item.Token) } out := errorz.Must(b.Bytes()) fmt.Printf("\n--- reformat ---\n%s\n----------\n", out) }
첫 번째 예에서는 JSON을 축소하고 두 번째 예에서는 접두사 "?"를 사용하여 형식을 지정합니다. 각 줄마다.
--- minify --- {"name":"Alice","age":24,"scores":[9,10,8],"address":{"city":"The Sun","zip":10101}} ---------- --- reformat --- ? { ? "name": "Alice", ? "age": 24, ? "scores": [ ? 9, ? 10, ? 8 ? ], ? "address": { ? "city": "The Sun", ? "zip": 10101 ? } ? } ----------
4. 줄 번호 추가
이 예에서는 fmt.Fprintf() 호출 앞에 b.WriteNewline()을 추가하여 JSON 출력에 줄 번호를 추가합니다. 예제/04.line_number를 참조하세요.
// ?Example: print with line number i := 0 b := iterjson.NewBuilder("", " ") for item, err := range iterjson.Parse(data) { i++ errorz.MustZ(err) b.WriteNewline(item.Token.Type()) // ? add line number fmt.Fprintf(b, "%3d ", i) b.Add(item.Key, item.Token) } out := errorz.Must(b.Bytes()) fmt.Printf("\n--- line number ---\n%s\n----------\n", out)
다음과 같이 출력됩니다:
1 { 2 "name": "Alice", 3 "age": 24, 4 "scores": [ 5 9, 6 10, 7 8 8 ], 9 "address": { 10 "city": "The Sun", 11 "zip": 10101 12 } 13 }
5. 코멘트 추가
b.WriteComma()와 b.WriteNewline() 사이에 fmt.Fprintf(comment)를 넣으면 각 줄의 끝에 주석을 추가할 수 있습니다. 예제/05.comment를 참조하세요.
i, newlineIdx, maxIdx := 0, 0, 30 b := iterjson.NewBuilder("", " ") for item, err := range iterjson.Parse(data) { errorz.MustZ(err) b.WriteComma(item.Token.Type()) // ? add comment if i > 0 { length := b.Len() - newlineIdx fmt.Fprint(b, strings.Repeat(" ", maxIdx-length)) fmt.Fprintf(b, "// %2d", i) } i++ b.WriteNewline(item.Token.Type()) newlineIdx = b.Len() // save the newline index b.Add(item.Key, item.Token) } length := b.Len() - newlineIdx fmt.Fprint(b, strings.Repeat(" ", maxIdx-length)) fmt.Fprintf(b, "// %2d", i) out := errorz.Must(b.Bytes()) fmt.Printf("\n--- comment ---\n%s\n----------\n", out)
다음과 같이 출력됩니다:
{ // 1 "name": "Alice", // 2 "age": 24, // 3 "scores": [ // 4 9, // 5 10, // 6 8 // 7 ], // 8 "address": { // 9 "city": "The Sun", // 10 "zip": 10101 // 11 } // 12 } // 13
6. JSON 필터링 및 값 추출
현재 항목의 경로를 가져오는 item.GetPathString() 및 item.GetRawPath()가 있습니다. 이를 사용하여 JSON 데이터를 필터링할 수 있습니다. 예제/06.filter_print를 참조하세요.
item.GetPathString() 및 정규 표현식의 예:
fmt.Printf("\n--- filter: GetPathString() ---\n") i := 0 for item, err := range iterjson.Parse(data) { i++ errorz.MustZ(err) path := item.GetPathString() switch { case path == "name", strings.Contains(path, "address"): // continue default: continue } // ? print with line number fmt.Printf("%2d %20s . %s\n", i, item.Token, item.GetPath()) }
item.GetRawPath() 및 path.Match()의 예:
fmt.Printf("\n--- filter: GetRawPath() ---\n") i := 0 for item, err := range iterjson.Parse(data) { i++ errorz.MustZ(err) path := item.GetRawPath() switch { case path.Match("name"), path.Contains("address"): // continue default: continue } // ? print with line number fmt.Printf("%2d %20s . %s\n", i, item.Token, item.GetPath()) }
두 예제 모두 다음과 같이 출력됩니다.
{ "name": "Alice", "age": 24, "scores": [9, 10, 8], "address": { "city": "The Sun", "zip": 10101 } }
7. JSON 필터링 및 새 JSON 반환
빌더를 SetSkipEmptyStructures(false) 옵션과 필터링 논리와 결합하면 JSON 데이터를 필터링하고 새 JSON을 반환할 수 있습니다. 예제/07.filter_json
을 참조하세요.
package main import ( "fmt" "ezpkg.io/errorz" iterjson "ezpkg.io/iter.json" ) func main() { data := `{"name": "Alice", "age": 24, "scores": [9, 10, 8], "address": {"city": "The Sun", "zip": 10101}}` // ?Example: iterate over json fmt.Printf("| %12v | %10v | %10v |%v|\n", "PATH", "KEY", "TOKEN", "LVL") fmt.Println("| ------------ | ---------- | ---------- | - |") for item, err := range iterjson.Parse([]byte(data)) { errorz.MustZ(err) fmt.Printf("| %12v | %10v | %10v | %v |\n", item.GetPathString(), item.Key, item.Token, item.Level) } }
이 예에서는 필터링된 필드만 포함된 새 JSON을 반환합니다.
| PATH | KEY | TOKEN |LVL| | ------------ | ---------- | ---------- | - | | | | { | 0 | | name | "name" | "Alice" | 1 | | age | "age" | 24 | 1 | | scores | "scores" | [ | 1 | | scores.0 | | 9 | 2 | | scores.1 | | 10 | 2 | | scores.2 | | 8 | 2 | | scores | | ] | 1 | | address | "address" | { | 1 | | address.city | "city" | "The Sun" | 2 | | address.zip | "zip" | 10101 | 2 | | address | | } | 1 | | | | } | 0 |
8. 값 편집
JSON 데이터의 값을 편집하는 예입니다. API에 숫자 ID를 사용한다고 가정합니다. ID가 너무 커서 JavaScript가 이를 처리할 수 없습니다. 이를 문자열로 변환해야 합니다. example/08.number_id 및 order.json을 참조하세요.
JSON 데이터를 반복하여 모든 _id 필드를 찾고 숫자 ID를 문자열로 변환합니다.
b := iterjson.NewBuilder("", " ") // open an object b.Add("", iterjson.TokenObjectOpen) // add a few fields b.Add("name", "Alice") b.Add("age", 22) b.Add("email", "alice@example.com") b.Add("phone", "(+84) 123-456-789") // open an array b.Add("languages", iterjson.TokenArrayOpen) b.Add("", "English") b.Add("", "Vietnamese") b.Add("", iterjson.TokenArrayClose) // close the array // accept any type that can marshal to json b.Add("address", Address{ HouseNumber: 42, Street: "Ly Thuong Kiet", City: "Ha Noi", Country: "Vietnam", }) // accept []byte as raw json b.Add("pets", []byte(`[{"type":"cat","name":"Kitty","age":2},{"type":"dog","name":"Yummy","age":3}]`)) // close the object b.Add("", iterjson.TokenObjectClose) out := errorz.Must(b.Bytes()) fmt.Printf("\n--- build json ---\n%s\n", out)
이렇게 하면 숫자 ID에 따옴표가 추가됩니다.
{ "name": "Alice", "age": 22, "email": "alice@example.com", "phone": "(+84) 123-456-789", "languages": [ "English", "Vietnamese" ], "address": {"house_number":42,"street":"Ly Thuong Kiet","city":"Ha Noi","country":"Vietnam"}, "pets": [ { "type": "cat", "name": "Kitty", "age": 2 }, { "type": "dog", "name": "Yummy", "age": 3 } ] }
결론
ezpkg.io/iter.json 패키지는 Go 개발자가 JSON 데이터를 정확하고 효율적으로 처리할 수 있도록 지원합니다. 복잡한 JSON 구조를 반복하고, 새로운 JSON 객체를 동적으로 구축하고, 데이터 형식을 지정하거나 축소하고, 특정 필드를 필터링하고, 값을 변환해야 하는 경우에도 iter.json은 유연하고 강력한 솔루션을 제공합니다.
데이터를 완전히 구문 분석할 필요 없이 효과적인 JSON 조작을 위한 도구로 이 패키지를 커뮤니티와 공유하게 되어 기쁩니다. 아직 초기 개발 단계이고 더 많은 기능을 추가할 여지가 있지만 이미 많은 일반적인 사용 사례에서 잘 작동하고 있습니다.
개선을 위한 구체적인 요구 사항이나 아이디어가 있는 경우 언제든지 문의해 주세요. 피드백을 듣고 사용 사례를 지원하는 데 도움을 드리고 싶습니다! ?
작가
올리버 응우옌 입니다. Go 및 JS를 사용하는 소프트웨어 엔지니어입니다. 나는 매일 더 나은 모습을 배우고 보는 것을 즐깁니다. 때때로 새로운 오픈 소스 프로젝트를 시작하세요. 여행 중에 지식과 생각을 공유해보세요.
해당 게시물은 Olivernguyen.io에도 게시되어 있습니다.
위 내용은 iter.json: Go에서 JSON을 반복하고 조작하는 강력하고 효율적인 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











보안 통신에 널리 사용되는 오픈 소스 라이브러리로서 OpenSSL은 암호화 알고리즘, 키 및 인증서 관리 기능을 제공합니다. 그러나 역사적 버전에는 알려진 보안 취약점이 있으며 그 중 일부는 매우 유해합니다. 이 기사는 데비안 시스템의 OpenSSL에 대한 일반적인 취약점 및 응답 측정에 중점을 둘 것입니다. DebianopensSL 알려진 취약점 : OpenSSL은 다음과 같은 몇 가지 심각한 취약점을 경험했습니다. 심장 출혈 취약성 (CVE-2014-0160) :이 취약점은 OpenSSL 1.0.1 ~ 1.0.1F 및 1.0.2 ~ 1.0.2 베타 버전에 영향을 미칩니다. 공격자는이 취약점을 사용하여 암호화 키 등을 포함하여 서버에서 무단 읽기 민감한 정보를 사용할 수 있습니다.

백엔드 학습 경로 : 프론트 엔드에서 백엔드 초보자로서 프론트 엔드에서 백엔드까지의 탐사 여행은 프론트 엔드 개발에서 변화하는 백엔드 초보자로서 이미 Nodejs의 기초를 가지고 있습니다.

Beegoorm 프레임 워크에서 모델과 관련된 데이터베이스를 지정하는 방법은 무엇입니까? 많은 Beego 프로젝트에서는 여러 데이터베이스를 동시에 작동해야합니다. Beego를 사용할 때 ...

Go Language의 부동 소수점 번호 작동에 사용되는 라이브러리는 정확도를 보장하는 방법을 소개합니다.

Go Crawler Colly의 대기열 스레딩 문제는 Colly Crawler 라이브러리를 GO 언어로 사용하는 문제를 탐구합니다. � ...

골란드의 사용자 정의 구조 레이블이 표시되지 않으면 어떻게해야합니까? Go Language 개발을 위해 Goland를 사용할 때 많은 개발자가 사용자 정의 구조 태그를 만날 것입니다 ...

Go Language에서 메시지 대기열을 구현하기 위해 Redisstream을 사용하는 문제는 Go Language와 Redis를 사용하는 것입니다 ...

이 기사는 데비안 시스템에서 MongoDB를 구성하여 자동 확장을 달성하는 방법을 소개합니다. 주요 단계에는 MongoDB 복제 세트 및 디스크 공간 모니터링 설정이 포함됩니다. 1. MongoDB 설치 먼저 MongoDB가 데비안 시스템에 설치되어 있는지 확인하십시오. 다음 명령을 사용하여 설치하십시오. sudoaptupdatesudoaptinstall-imongb-org 2. MongoDB Replica 세트 MongoDB Replica 세트 구성은 자동 용량 확장을 달성하기위한 기초 인 고 가용성 및 데이터 중복성을 보장합니다. MongoDB 서비스 시작 : sudosystemctlstartMongodsudosys
