Skip to content

Instantly share code, notes, and snippets.

@tony612
Created January 10, 2025 02:36
Show Gist options
  • Save tony612/9237287f42649cdc5eb29f855638510c to your computer and use it in GitHub Desktop.
Save tony612/9237287f42649cdc5eb29f855638510c to your computer and use it in GitHub Desktop.
json_parse_compare
// 嵌套 JSON 解析耗时: 491.875µs
// 打平 JSON 解析耗时: 67.083µs
package main
import (
"encoding/json"
"fmt"
"time"
)
// 嵌套结构体
type NestedCompany struct {
Company struct {
Name string `json:"name"`
Employees []struct {
ID int `json:"id"`
Name string `json:"name"`
Department struct {
Name string `json:"name"`
Location string `json:"location"`
} `json:"department"`
Projects []struct {
Name string `json:"name"`
Status string `json:"status"`
} `json:"projects"`
} `json:"employees"`
} `json:"company"`
}
// 打平结构体
type FlatCompany struct {
CompanyName string `json:"company_name"`
Employees []struct {
EmployeeID int `json:"employee_id"`
EmployeeName string `json:"employee_name"`
DepartmentName string `json:"department_name"`
DepartmentLocation string `json:"department_location"`
Projects []struct {
ProjectName string `json:"project_name"`
ProjectStatus string `json:"project_status"`
} `json:"projects"`
} `json:"employees"`
}
func main() {
nestedJSON := `{
"company": {
"name": "Tech Corp",
"employees": [
{
"id": 1,
"name": "Alice",
"department": {
"name": "Engineering",
"location": "New York"
},
"projects": [
{
"name": "Project A",
"status": "In Progress"
},
{
"name": "Project B",
"status": "Completed"
}
]
},
{
"id": 2,
"name": "Bob",
"department": {
"name": "Marketing",
"location": "San Francisco"
},
"projects": [
{
"name": "Project C",
"status": "In Progress"
}
]
}
]
}
}`
flatJSON := `{
"company_name": "Tech Corp",
"employees": [
{
"employee_id": 1,
"employee_name": "Alice",
"department_name": "Engineering",
"department_location": "New York",
"projects": [
{
"project_name": "Project A",
"project_status": "In Progress"
},
{
"project_name": "Project B",
"project_status": "Completed"
}
]
},
{
"employee_id": 2,
"employee_name": "Bob",
"department_name": "Marketing",
"department_location": "San Francisco",
"projects": [
{
"project_name": "Project C",
"project_status": "In Progress"
}
]
}
]
}`
// 测试嵌套 JSON 解析
start := time.Now()
var nestedCompany NestedCompany
_ = json.Unmarshal([]byte(nestedJSON), &nestedCompany)
fmt.Printf("嵌套 JSON 解析耗时: %v\n", time.Since(start))
// 测试打平 JSON 解析
start = time.Now()
var flatCompany FlatCompany
_ = json.Unmarshal([]byte(flatJSON), &flatCompany)
fmt.Printf("打平 JSON 解析耗时: %v\n", time.Since(start))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment