paint-brush
Go'dagi yangi xususiyat JSON ma'lumotlarini takrorlashni, manipulyatsiya qilishni osonlashtiraditomonidan@olvrng
Yangi tarix

Go'dagi yangi xususiyat JSON ma'lumotlarini takrorlashni, manipulyatsiya qilishni osonlashtiradi

tomonidan Oliver Nguyen13m2024/12/17
Read on Terminal Reader

Juda uzoq; O'qish

Agar siz JSON ma'lumotlaringizni aylanib chiqsangiz, har bir elementning yo'lini bilib olsangiz va u bilan tezda nima qilishni hal qilsangiz nima bo'ladi?
featured image - Go'dagi yangi xususiyat JSON ma'lumotlarini takrorlashni, manipulyatsiya qilishni osonlashtiradi
Oliver Nguyen HackerNoon profile picture

Go'da tuzilmagan JSON ma'lumotlarini o'zgartirishingiz kerak bo'lganmi? Ehtimol, siz parolni va qora roʻyxatga kiritilgan barcha maydonlarni oʻchirishingiz, kalitlarni camelCase dan snake_case ga oʻzgartirishingiz yoki barcha raqam identifikatorlarini satrlarga aylantirishingiz kerak boʻlgandir, chunki JavaScript int64 yoqtirmaydi ? Agar sizning yechimingiz encoding/json yordamida hamma narsani map[string]any oʻchirib , soʻngra uni qayta tiklash boʻlsa... mayli, tan olaylik, bu samarali emas!


Agar siz JSON ma'lumotlarini aylanib chiqsangiz, har bir elementning yo'lini bilib olsangiz va u bilan tezda nima qilishni hal qilsangiz nima bo'ladi?


Ha! Menda yaxshi xabar bor! Go 1.23 da yangi iterator funksiyasi bilan JSONni takrorlash va manipulyatsiya qilishning eng yaxshi usuli mavjud. Go'da JSON bilan ishlashda kuchli va samarali hamkoringiz — ezpkg.io/iter.json bilan tanishing.


1. JSONni takrorlash

Bizda alice.json fayli borligini hisobga olsak:

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


Birinchidan, JSON faylida takrorlash uchun for range Parse() foydalanamiz, so'ngra har bir elementning yo'lini, kalitini, tokenini va darajasini chop etamiz. Misollarga qarang/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) } }


Kod chiqadi:

 | 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 qurish

JSON ma'lumotlarini yaratish uchun Builder foydalaning. U cheklash uchun ixtiyoriy argumentlarni qabul qiladi. Misollarga qarang/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)


JSON ni chekinish bilan chiqaradi:

 { "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. JSON formatlash

Siz JSON ma'lumotlarini uning kaliti va qiymatlarini Builder yuborish orqali qayta qurishingiz yoki formatlashingiz mumkin. Misollarga qarang/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) }


Birinchi misol JSON-ni kichraytiradi, ikkinchi misol esa uni har bir satrda "👉" prefiksi bilan formatlaydi.

 --- 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. Satr raqamlarini qo'shish

Bu misolda fmt.Fprintf() chaqiruvidan oldin b.WriteNewline() ni qo'shish orqali JSON chiqishiga satr raqamlarini qo'shamiz. Misollarga qarang/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)


Bu chiqadi:

 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. Izoh qo'shish

b.WriteComma() va b.WriteNewline() orasiga fmt.Fprintf(comment) qo'yish orqali siz har bir satr oxiriga izoh qo'shishingiz mumkin. Misollarga qarang/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)


Bu chiqadi:

 { // 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. JSONni filtrlash va qiymatlarni chiqarish

Joriy elementning yo'lini olish uchun item.GetPathString() va item.GetRawPath() mavjud. Ulardan JSON ma'lumotlarini filtrlash uchun foydalanishingiz mumkin. Misollarga qarang/06.filter_print .


item.GetPathString() va regexp bilan misol:

 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() va path.Match() bilan misol:

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


Ikkala misol ham chiqadi:

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

7. JSONni filtrlash va yangi JSONni qaytarish

Builder SetSkipEmptyStructures(false) opsiyasi va filtrlash mantig'i bilan birlashtirib, siz JSON ma'lumotlarini filtrlashingiz va yangi JSONni qaytarishingiz mumkin. Misollarga qarang/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)


Ushbu misol faqat filtrlangan maydonlar bilan yangi JSONni qaytaradi:

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

8. Qiymatlarni tahrirlash

Bu JSON ma'lumotlaridagi qiymatlarni tahrirlash uchun misol. Aytaylik, biz API uchun raqam identifikatorlaridan foydalanmoqdamiz. Idlar juda katta va JavaScript ularni boshqara olmaydi. Biz ularni satrlarga aylantirishimiz kerak. Misollarga qarang/08.number_id va order.json .


JSON ma'lumotlarini takrorlang, barcha _id maydonlarini toping va raqam identifikatorlarini satrlarga aylantiring:

 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)


Bu raqam identifikatorlariga tirnoq qo'shadi:

 { "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 } ] }

Xulosa

ezpkg.io/iter.json to'plami Go dasturchilariga JSON ma'lumotlarini aniqlik va samaradorlik bilan qayta ishlash imkoniyatini beradi. Murakkab JSON tuzilmalari orqali takrorlash, dinamik ravishda yangi JSON obyektlarini yaratish, maʼlumotlarni formatlash yoki kichiklashtirish, muayyan maydonlarni filtrlash yoki hatto qiymatlarni oʻzgartirish kerak boʻladimi, iter.json moslashuvchan va kuchli yechim taklif qiladi.


Men ushbu paketni maʼlumotlarni toʻliq tahlil qilmasdan samarali JSON manipulyatsiyasi vositasi sifatida hamjamiyat bilan baham koʻrishdan xursandman. U hali erta ishlab chiqilayotgan bo'lsa-da va qo'shimcha funktsiyalar uchun joy mavjud bo'lsa-da, u ko'plab umumiy foydalanish holatlarida yaxshi ishlaydi.


Agar sizda aniq talablar yoki takomillashtirish bo'yicha g'oyalaringiz bo'lsa, bemalol bog'laning — fikr-mulohazalaringizni eshitishni va foydalanish holatlaringizni qo'llab-quvvatlashni istardim! 🥳



Muallif

Men Oliver Nguyenman. Go va JS bilan ishlaydigan dasturiy ta'minot muhandisi. Men har kuni o'zimni yaxshiroq ko'rishni va o'rganishni yoqtiraman. Vaqti-vaqti bilan yangi ochiq manbali loyihalarni ajratib oling. Sayohatim davomida bilim va fikrlarimni baham ko'ring.


Xabar ham e'lon qilingan olivenguyen.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.

TEGI QILISH

USHBU MAQOLA TAQDIM ETILGAN...