搜尋
首頁後端開發Golang如何在 Golang 中解析 JSON 資料?

Golang 解析 JSON 資料包含四個主要步驟:導入 आवश्यक包,包含 json、fmt 和 ioutil。從檔案中讀取 JSON 資料。將 JSON 資料解碼到結構體或 map 中。存取 map 中的鍵值對或使用解碼的結構體。

如何在 Golang 中解析 JSON 数据?

如何在Golang 中解析JSON 資料

Golang 提供了強大的工具來處理JSON 數據,可以透過以下步驟實作:

#1. 匯入必要的套件

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
)

2. 從檔案讀取JSON 資料

jsonFile, err := ioutil.ReadFile("data.json")
if err != nil {
    fmt.Println("Error reading JSON file:", err)
    return
}

3. 解碼JSON 資料到結構體或map

#解碼到結構體:

type Person struct {
    Name string
    Age  int
}

var person Person
err = json.Unmarshal(jsonFile, &person)
if err != nil {
    fmt.Println("Error decoding JSON data:", err)
    return
}

解碼到map 中:

var data map[string]interface{}
err = json.Unmarshal(jsonFile, &data)
if err != nil {
    fmt.Println("Error decoding JSON data:", err)
    return
}

// 访问 map中的键值对
fmt.Println("Name:", data["Name"])

實戰案例

讀取JSON 檔案並列印姓名和年齡:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
)

type Person struct {
    Name string
    Age  int
}

func main() {
    jsonFile, err := ioutil.ReadFile("data.json")
    if err != nil {
        fmt.Println("Error reading JSON file:", err)
        return
    }

    var person Person
    err = json.Unmarshal(jsonFile, &person)
    if err != nil {
        fmt.Println("Error decoding JSON data:", err)
        return
    }

    fmt.Printf("Name: %s, Age: %d\n", person.Name, person.Age)
}

將以下JSON 資料儲存到檔案中:

{
  "Name": "John Doe",
  "Age": 30
}

然後執行程序,輸出如下:

Name: John Doe, Age: 30

以上是如何在 Golang 中解析 JSON 資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
初始功能和副作用:平衡初始化與可維護性初始功能和副作用:平衡初始化與可維護性Apr 26, 2025 am 12:23 AM

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

開始GO:初學者指南開始GO:初學者指南Apr 26, 2025 am 12:21 AM

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

進行並發模式:開發人員的最佳實踐進行並發模式:開發人員的最佳實踐Apr 26, 2025 am 12:20 AM

開發者應遵循以下最佳實踐:1.謹慎管理goroutines以防止資源洩漏;2.使用通道進行同步,但避免過度使用;3.在並發程序中顯式處理錯誤;4.了解GOMAXPROCS以優化性能。這些實踐對於高效和穩健的軟件開發至關重要,因為它們確保了資源的有效管理、同步的正確實現、錯誤的適當處理以及性能的優化,從而提升軟件的效率和可維護性。

進行生產:現實世界的用例和示例進行生產:現實世界的用例和示例Apr 26, 2025 am 12:18 AM

Goexcelsinproductionduetoitsperformanceandsimplicity,butrequirescarefulmanagementofscalability,errorhandling,andresources.1)DockerusesGoforefficientcontainermanagementthroughgoroutines.2)UberscalesmicroserviceswithGo,facingchallengesinservicemanageme

go中的自定義錯誤類型:提供詳細的錯誤信息go中的自定義錯誤類型:提供詳細的錯誤信息Apr 26, 2025 am 12:09 AM

我們需要自定義錯誤類型,因為標準錯誤接口提供的信息有限,自定義類型能添加更多上下文和結構化信息。 1)自定義錯誤類型能包含錯誤代碼、位置、上下文數據等,2)提高調試效率和用戶體驗,3)但需注意其複雜性和維護成本。

使用GO編程語言構建可擴展系統使用GO編程語言構建可擴展系統Apr 25, 2025 am 12:19 AM

goisidealforbuildingscalablesystemsduetoitssimplicity,效率和建築物內currencysupport.1)go'scleansyntaxandaxandaxandaxandMinimalisticDesignenhanceProductivityAndRedCoductivityAndRedCuceErr.2)ItSgoroutinesAndInesAndInesAndInesAndineSandChannelsEnablenableNablenableNableNablenableFifficConcurrentscorncurrentprogragrammentworking torkermenticmminging

有效地使用Init功能的最佳實踐有效地使用Init功能的最佳實踐Apr 25, 2025 am 12:18 AM

Initfunctionsingorunautomationbeforemain()andareusefulforsettingupenvorments和InitializingVariables.usethemforsimpletasks,避免使用輔助效果,andbecautiouswithTestingTestingTestingAndLoggingTomaintAnainCodeCodeCodeClarityAndTestesto。

INIT函數在GO軟件包中的執行順序INIT函數在GO軟件包中的執行順序Apr 25, 2025 am 12:14 AM

goinitializespackagesintheordertheordertheyimported,thenexecutesInitFunctionswithinApcageIntheirdeFinityOrder,andfilenamesdetermineTheOrderAcractacractacrosmultiplefiles.thisprocessCanbeCanbeinepessCanbeInfleccessByendercrededBydeccredByDependenciesbetenciesbetencemendencenciesbetnependendpackages,whermayleLeadtocomplexinitialitialializizesizization

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)