Preflight Checklist

  • [X] I have searched the issue tracker for an issue that matches the one I want to file, without success.
  • [X] I am not looking for support or already pursued the available support channels without success.
  • [X] I have checked the troubleshooting guide for my problem, without success.

Viper Version

1.19.0

Go Version

1.23.3

Config Source

Files

Format

JSON

Repl.it link

No response

Code reproducing the issue

package main

import (
    "fmt"
    "io"
    "os"
)
import "github.com/spf13/viper"

func printConfig() {
    f, err := os.OpenFile("./config.json", os.O_RDONLY, os.ModePerm)
    if err != nil {
        panic(err)
    }
    data, err := io.ReadAll(f)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(data))
}

func main() {
    printConfig()
    viper.SetConfigName("config")
    viper.SetConfigType("json")
    viper.AddConfigPath(".")
    err := viper.ReadInConfig()
    if err != nil {
        panic(fmt.Errorf("fatal error config file: %w", err))
    }
    viper.Set("person.0.detail.age", 29)
    err = viper.WriteConfig()
    if err != nil {
        panic(fmt.Errorf("fatal error config file: %w", err))
    }
    printConfig()
}

Expected Behavior

source config json file

{
  "person": [
    {
      "detail": {
        "age": 18
      }
    }
  ]
}

after call function

viper.Set("person.0.detail.age", 29)

this config file should be

{
  "person": [
    {
      "detail": {
        "age": 29
      }
    }
  ]
}

Actual Behavior

source config json file

{
  "person": [
    {
      "detail": {
        "age": 18
      }
    }
  ]
}

after call function

viper.Set("person.0.detail.age", 29)

this config file was changed like this

{
  "person": {
    "0": {
      "detail": {
        "age": 29
      }
    }
  }
}

Steps To Reproduce

1.create config.json in current project directory and input content json { "person": [ { "detail": { "age": 18 } } ] }

2.go run main.go

3.watch the config.json data

Additional Information

In some programming languages like JavaScript, maybe person[0] is same to person["0"], but the changed of 'data struct' maybe cause confused issues.

Comment From: chengxilo

I think the best solution is to make viper support syntax like viper.Set("person[0].detail.age", 29), use [] to represent that we wanna to change the element of which index is 0. To avoid the strange behavior.

Comment From: github-actions[bot]

Issues with no activity for 30 days are marked stale and subject to being closed.