You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go语言如何将JSON中active字段名改为inactive并保留值及附加新值

Solution to Rename "active" to "inactive" in JSON and Add New Fields in Go

I’ll walk you through two practical approaches depending on whether your JSON structure is fixed (known in advance) or dynamic.

Approach 1: Using Structs (Type-Safe for Fixed Schemas)

If you know the exact structure of your JSON ahead of time, structs are the cleanest, safest choice. Here’s how to implement the field rename and add new fields:

package main

import (
	"encoding/json"
	"fmt"
)

// Original struct matching your input JSON structure
type OriginalData struct {
	Active bool   `json:"active"`
	Name   string `json:"name"`
	// Add any other existing fields here
}

// Modified struct with renamed field and new field
type ModifiedData struct {
	Inactive bool   `json:"inactive"`
	Name     string `json:"name"`
	NewField string `json:"new_field"` // New field to append
	// Keep other existing fields from OriginalData
}

func main() {
	// Sample input JSON
	inputJSON := `{"active": true, "name": "test_user"}`

	// Unmarshal JSON into the original struct
	var original OriginalData
	err := json.Unmarshal([]byte(inputJSON), &original)
	if err != nil {
		fmt.Println("Error parsing JSON:", err)
		return
	}

	// Convert to modified struct, preserving the "active" value as "inactive"
	modified := ModifiedData{
		Inactive: original.Active,
		Name:     original.Name,
		NewField: "sample_new_value", // Set your desired new field value here
	}

	// Marshal back to formatted JSON
	outputJSON, err := json.MarshalIndent(modified, "", "  ")
	if err != nil {
		fmt.Println("Error generating JSON:", err)
		return
	}

	fmt.Println("Modified JSON:")
	fmt.Println(string(outputJSON))
}

Approach 2: Using map[string]interface{} (For Dynamic JSON)

If your JSON structure varies or isn’t known upfront, using a map gives you the flexibility to modify keys dynamically:

package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	// Sample input JSON with dynamic fields
	inputJSON := `{"active": false, "age": 28, "email": "user@example.com"}`

	// Unmarshal JSON into a map
	var data map[string]interface{}
	err := json.Unmarshal([]byte(inputJSON), &data)
	if err != nil {
		fmt.Println("Error parsing JSON:", err)
		return
	}

	// Rename "active" to "inactive" while keeping its value
	if val, exists := data["active"]; exists {
		delete(data, "active")
		data["inactive"] = val
	}

	// Add your new field here
	data["new_field"] = "dynamic_custom_value"

	// Marshal back to formatted JSON
	outputJSON, err := json.MarshalIndent(data, "", "  ")
	if err != nil {
		fmt.Println("Error generating JSON:", err)
		return
	}

	fmt.Println("Modified JSON:")
	fmt.Println(string(outputJSON))
}

Key Notes:

  • Struct Approach: Best for fixed schemas—it provides type safety and catches errors at compile time.
  • Map Approach: Ideal for dynamic JSON where fields might change. Just be mindful of type assertions if you need to manipulate specific field values later.

Testing with Go Playground

You can copy either code snippet into the official Go Playground (no external links needed—just search for "Go Playground" online) to run and tweak it with your own JSON input.

内容的提问来源于stack exchange,提问作者user7026738

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:23:47