JSON data can be saved to a MySQL database by using the gjson library or the json.Unmarshal function. The gjson library provides convenience methods for parsing JSON fields, and the json.Unmarshal function requires a target type pointer to unmarshal JSON data. Both methods require preparing SQL statements and performing insert operations to persist the data into the database.
How to save JSON data to the database in Golang
Introduction
In Golang , saving JSON data to a database is a common task. This article will explore different methods of persisting JSON data using commonly used databases such as MySQL, and provide practical examples for reference.
Using the gjson library
The gjson library is a popular Golang package for parsing and manipulating JSON data. It provides easy methods to parse JSON data into Go data structures such as maps and slices.
package main import ( "database/sql" "encoding/json" "fmt" _ "github.com/go-sql-driver/mysql" "github.com/tidwall/gjson" ) func main() { db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/database") if err != nil { panic(err) } defer db.Close() jsonData := `{ "name": "John Doe", "age": 30, "address": { "street": "Main Street", "city": "New York" } }` values := []interface{}{} // 解析 JSON 字段 name := gjson.Get(jsonData, "name").String() age := gjson.Get(jsonData, "age").Int() address := gjson.Get(jsonData, "address").String() values = append(values, name, age, address) // 準(zhǔn)備 SQL 語(yǔ)句 stmt, err := db.Prepare("INSERT INTO users (name, age, address) VALUES (?, ?, ?)") if err != nil { panic(err) } // 執(zhí)行插入操作 _, err = stmt.Exec(values...) if err != nil { panic(err) } fmt.Println("JSON data saved to database successfully") }
Using json.Unmarshal
The json.Unmarshal function is part of the Golang standard library and is used to unmarshal JSON data into Go variables. This method requires a target type pointer as the second parameter.
package main import ( "database/sql" "encoding/json" "fmt" _ "github.com/go-sql-driver/mysql" ) func main() { db, err := sql.Open("mysql", "user:password@tcp(localhost:3306)/database") if err != nil { panic(err) } defer db.Close() jsonData := `{ "name": "John Doe", "age": 30, "address": { "street": "Main Street", "city": "New York" } }` var user struct { Name string Age int Address string } err = json.Unmarshal([]byte(jsonData), &user) if err != nil { panic(err) } // 準(zhǔn)備 SQL 語(yǔ)句 stmt, err := db.Prepare("INSERT INTO users (name, age, address) VALUES (?, ?, ?)") if err != nil { panic(err) } // 執(zhí)行插入操作 _, err = stmt.Exec(user.Name, user.Age, user.Address) if err != nil { panic(err) } fmt.Println("JSON data saved to database successfully") }
The above is the detailed content of How to save JSON data to database in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Oracle is not only a database company, but also a leader in cloud computing and ERP systems. 1. Oracle provides comprehensive solutions from database to cloud services and ERP systems. 2. OracleCloud challenges AWS and Azure, providing IaaS, PaaS and SaaS services. 3. Oracle's ERP systems such as E-BusinessSuite and FusionApplications help enterprises optimize operations.

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Redis is a memory data structure storage system, mainly used as a database, cache and message broker. Its core features include single-threaded model, I/O multiplexing, persistence mechanism, replication and clustering functions. Redis is commonly used in practical applications for caching, session storage, and message queues. It can significantly improve its performance by selecting the right data structure, using pipelines and transactions, and monitoring and tuning.

MongoDB's future is full of possibilities: 1. The development of cloud-native databases, 2. The fields of artificial intelligence and big data are focused, 3. The improvement of security and compliance. MongoDB continues to advance and make breakthroughs in technological innovation, market position and future development direction.

Redis is superior to traditional databases in high concurrency and low latency scenarios, but is not suitable for complex queries and transaction processing. 1.Redis uses memory storage, fast read and write speed, suitable for high concurrency and low latency requirements. 2. Traditional databases are based on disk, support complex queries and transaction processing, and have strong data consistency and persistence. 3. Redis is suitable as a supplement or substitute for traditional databases, but it needs to be selected according to specific business needs.

The main difference between Navicat's CommunityEdition and CommercialVersions is the functionality and usage scenarios. CommunityEdition provides basic database management functions that are suitable for basic needs; CommercialVersions includes advanced functions, such as data model design and automation tasks, suitable for professional needs.

RSS chose XML instead of JSON because: 1) XML's structure and verification capabilities are better than JSON, which is suitable for the needs of RSS complex data structures; 2) XML was supported extensively at that time; 3) Early versions of RSS were based on XML and have become a standard.
