Go json문자열에서 특정 키의 값 바꾸기

1 개요[ | ]

Go json문자열에서 특정 키의 값 바꾸기

2 단순[ | ]

package main

import (
	"encoding/json"
	"fmt"
)

func updateKeyValue(data []byte, key, newValue string) ([]byte, error) {
	var m map[string]interface{}
	err := json.Unmarshal(data, &m)
	if err != nil {
		return nil, fmt.Errorf("json unmarshal error: %w", err)
	}

	m[key] = newValue

	return json.Marshal(m)
}

func main() {
	jsonString := `{"name": "John Doe", "age": 30, "city": "New York"}`
	keyToUpdate := "age"
	newValue := "35"

	updatedJson, err := updateKeyValue([]byte(jsonString), keyToUpdate, newValue)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	fmt.Println(string(updatedJson)) // 출력: {"name": "John Doe", "age": "35", "city": "New York"}
}

3 중첩[ | ]

package main

import (
	"encoding/json"
	"fmt"
	"strings"
)

func updateNestedKeyValue(data []byte, keyPath, newValue string) ([]byte, error) {
	var m map[string]interface{}
	err := json.Unmarshal(data, &m)
	if err != nil {
		return nil, fmt.Errorf("json unmarshal error: %w", err)
	}

	keys := strings.Split(keyPath, ".")
	currentLevel := m
	for i, key := range keys {
		if i == len(keys)-1 {
			currentLevel[key] = newValue
		} else {
			if _, ok := currentLevel[key]; !ok {
				currentLevel[key] = make(map[string]interface{})
			}
			currentLevel = currentLevel[key].(map[string]interface{})
		}
	}

	return json.Marshal(m)
}

func main() {
	jsonString := `{"name": "John Doe", "address": {"street": "123 Main St", "city": "New York"}}`
	keyPath := "address.city"
	newValue := "Los Angeles"

	updatedJson, err := updateNestedKeyValue([]byte(jsonString), keyPath, newValue)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	fmt.Println(string(updatedJson)) // 출력: {"name": "John Doe", "address": {"street": "123 Main St", "city": "Los Angeles"}}
}

4 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}