paint-brush
Uphawu olutsha kwi-Go lwenza kube lula ukuphindaphinda, ukuLawula iDatha ye-JSONnge@olvrng
Imbali entsha

Uphawu olutsha kwi-Go lwenza kube lula ukuphindaphinda, ukuLawula iDatha ye-JSON

nge Oliver Nguyen13m2024/12/17
Read on Terminal Reader

Inde kakhulu; Ukufunda

Kuthekani ukuba unokulophu kwidatha yakho ye-JSON, ubambe umendo wento nganye, kwaye uthathe isigqibo malunga nokuba wenze ntoni ngayo kubhabho?
featured image - Uphawu olutsha kwi-Go lwenza kube lula ukuphindaphinda, ukuLawula iDatha ye-JSON
Oliver Nguyen HackerNoon profile picture

Ngaba ukhe wafuna ukulungisa idatha ye-JSON engacwangciswanga kwi-Go? Mhlawumbi kuye kwafuneka ucime igama eligqithisiweyo kunye nawo onke amasimi avaliweyo, qamba kabusha izitshixo ukusuka camelCase ukuya kwi snake_case , okanye uguqule zonke ii-id zamanani zibe yimitya kuba iJavaScript ayiyithandi int64 ? Ukuba isisombululo sakho ibikukungamashanga yonke into kwimephu map[string]any usebenzisa encoding/json kwaye emva koko uyi-marshal umva... kulungile, masijongane nayo, ikude nokusebenza!


Kuthekani ukuba unokulophu kwidatha ye-JSON, ubambe umendo wento nganye, kwaye uthathe isigqibo malunga nokuba wenze ntoni ngayo kubhabho?


Ewe! Ndineendaba ezimnandi! Ngenqaku elitsha le-iterator kwi-Go 1.23, kukho indlela engcono yokuphindaphinda kunye nokukhohlisa i-JSON. Dibana ezpkg.io/iter.json — iqabane lakho elinamandla nelisebenzayo lokusebenza no-JSON kwi-Go.


1. Ukuhlaziya i-JSON

Ngenxa yokuba sinefayile ye alice.json :

 { "name": "Alice", "age": 24, "scores": [9, 10, 8], "address": { "city": "The Sun", "zip": 10101 } }


Kuqala, masisebenzise for range Parse() ukuphindaphinda ngaphezulu kwefayile ye-JSON, emva koko siprinte umendo, isitshixo, uphawu, kunye nenqanaba lento nganye. Jonga imizekelo/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) } }


Ikhowudi iya kukhupha:

 | 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. Ukwakha i-JSON

Sebenzisa Builder ukwakha idatha ye-JSON. Yamkela iingxoxo ozikhethelayo zokuhlehlisa. Jonga imizekelo/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", "[email protected]") 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)


Yintoni eya kukhupha i-JSON nge-indentation:

 { "name": "Alice", "age": 22, "email": "[email protected]", "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. Ukufomatha i-JSON

Unokwakha kwakhona okanye ukufomatha idatha ye-JSON ngokuthumela isitshixo sayo kunye nexabiso Builder . Jonga imizekelo/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) }


Umzekelo wokuqala unciphisa i-JSON ngelixa umzekelo wesibini uwufomatha ngesimaphambili "👉" kumgca ngamnye.

 --- 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. Ukongeza amanani emigca

Kulo mzekelo, songeza amanani omgca kwimveliso ye-JSON, ngokongeza i- b.WriteNewline() phambi kwe fmt.Fprintf() ifowuni. Jonga imizekelo/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)


Oku kuya kukhupha:

 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. Ukongeza izimvo

Ngokubeka i fmt.Fprintf(comment) phakathi kwe b.WriteComma() kunye ne b.WriteNewline() , unokongeza inkcazo ekupheleni komgca ngamnye. Jonga imizekelo/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)


Oku kuya kukhupha:

 { // 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. Ukucoca i-JSON kunye nokukhupha amaxabiso

Kukho item.GetPathString() kunye item.GetRawPath() ukufumana umendo wento yangoku. Unokuzisebenzisa ukucoca idatha ye-JSON. Jonga imizekelo/06.filter_print .


Umzekelo ngento.GetPathString item.GetPathString() kunye regexp :

 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()) }


Umzekelo ngento.GetRawPath item.GetRawPath() kunye 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()) }


Yomibini imizekelo iya kukhupha:

 2 "Alice" . name 9 { . address 10 "The Sun" . address.city 11 10101 . address.zip 12 } . address

7. Ukucoca i-JSON kunye nokubuyisela i-JSON entsha

Ngokudibanisa i Builder kunye nokhetho lwe SetSkipEmptyStructures(false) kunye nengqiqo yokucoca, unokucoca idatha ye-JSON kwaye ubuyisele i-JSON entsha. Jonga imizekelo/07.filter_json

 // 🦁Example: filter and output json b := iterjson.NewBuilder("", " ") b.SetSkipEmptyStructures(true) // 👉 skip empty [] or {} for item, err := range iterjson.Parse(data) { errorz.MustZ(err) if item.Token.IsOpen() || item.Token.IsClose() { b.Add(item.Key, item.Token) continue } path := item.GetPathString() switch { case path == "name", strings.Contains(path, "address"): // continue default: continue } b.Add(item.Key, item.Token) } out := errorz.Must(b.Bytes()) fmt.Printf("\n--- filter: output json ---\n%s\n----------\n", out)


Lo mzekelo uzakubuyisela i-JSON entsha enemihlaba ehluziweyo kuphela:

 { "name": "Alice", "address": { "city": "The Sun", "zip": 10101 } }

8. Amaxabiso okuhlela

Lo ngumzekelo wokuhlela amaxabiso kwidatha ye-JSON. Cinga ukuba sisebenzisa ii-id zenombolo kwi-API yethu. Izazisi zikhulu kakhulu kwaye iJavaScript ayikwazi ukuzibamba. Kufuneka siziguqule zibe yimicu. Jonga imizekelo/08.number_id kunye ne-oda.json .


Phinda ngaphezulu kwedatha ye-JSON, fumana zonke _id iindawo kwaye uguqule ii-id zenombolo zibe yimitya:

 b := iterjson.NewBuilder("", " ") for item, err := range iterjson.Parse(data) { errorz.MustZ(err) key, _ := item.GetRawPath().Last().ObjectKey() if strings.HasSuffix(key, "_id") { id, err0 := item.Token.GetInt() if err0 == nil { b.Add(item.Key, strconv.Itoa(id)) continue } } b.Add(item.Key, item.Token) } out := errorz.Must(b.Bytes()) fmt.Printf("\n--- convert number id ---\n%s\n----------\n", out)


Oku kuyakongeza iingcaphuno kwii-ID zamanani:

 { "order_id": "12345678901234", "number": 12, "customer_id": "12345678905678", "items": [ { "item_id": "12345678901042", "quantity": 1, "price": 123.45 }, { "item_id": "12345678901098", "quantity": 2, "price": 234.56 } ] }

Ukuqukumbela

Iphakheji ye-ezpkg.io/iter.json ixhobisa abaphuhlisi be-Go ukuphatha idatha ye-JSON ngokuchanekileyo kunye nokusebenza kakuhle. Nokuba ufuna ukuphindaphinda ngokusebenzisa izakhiwo ezintsonkothileyo ze-JSON, ukwakha izinto ezintsha ze-JSON ngokuguquguqukayo, ukufomatha okanye ukunciphisa idatha, ukucoca amasimi athile, okanye ukuguqula amaxabiso, iter.json ibonelela ngesisombululo esiguquguqukayo nesinamandla.


Ndiyavuya ukwabelana ngale phakheji noluntu njengesixhobo sokukhohlisa okusebenzayo kwe-JSON ngaphandle kwesidingo sokwahlula ngokupheleleyo idatha. Ngelixa isekuphuhliso lokuqala kwaye kukho indawo yeempawu ezingaphezulu, sele isebenza kakuhle kwiimeko ezininzi zokusetyenziswa okuqhelekileyo.


Ukuba uneemfuno ezithile okanye izimvo zokuphucula, zive ukhululekile ukufikelela - ndingathanda ukuva impendulo yakho kwaye ndincede ukuxhasa iimeko zakho zokusetyenziswa! 🥳



Umbhali

NdinguOliver Nguyen. Injineli yesoftware esebenza neGo kunye neJS. Ndiyakonwabela ukufunda kwaye ndibone inguqulelo yam engcono yonke imihla. Ngamanye amaxesha vula iiprojekthi ezintsha zomthombo ovulekileyo. Yabelana ngolwazi kunye neengcinga ngexesha lohambo lwam.


Isithuba sikwapapashwa apha olivernguyen.io .

L O A D I N G
. . . comments & more!

About Author

Oliver Nguyen HackerNoon profile picture
Oliver Nguyen@olvrng
I’m a software maker working mostly in Go and JavaScript. Share knowledge and thoughts during my journey.

ZIJONGE IIMPAWU

ELI NQAKU LINIKEZELWE KU...