tidwall / sjson

Set JSON values very quickly in Go
MIT License
2.4k stars 165 forks source link

Cannot delete an empty key from a JSON object #77

Open deathiop opened 6 months ago

deathiop commented 6 months ago

Hello,

That's quite obvious given the beginning of sjson.set, but one cannot delete an empty key from a JSON object using sjson. Though, this is a valid key, and gjson is able to manipulate its value:

package main

import (
    "encoding/json"
    "fmt"

    "github.com/tidwall/gjson"
    "github.com/tidwall/sjson"
)

const data = `{"name":{"first":"Janet","last":"Prichard"},"age":47, "": "foo"}`

func main() {
    var out map[string]any
    if err := json.Unmarshal([]byte(data), &out); err != nil {
        panic(fmt.Sprintf("Invalid JSON: %v", err))
    }
    fmt.Printf("Valid JSON, parsed Data: %v\n\n", out)

    result := gjson.Get(data, "")
    fmt.Printf("Fetched empty key from GJSON: %#v\n\n", result)

    value, err := sjson.Delete(data, "")
    fmt.Printf("New JSON string after SJSON: %s\n", value)
    fmt.Printf("SJSON error: %v\n", err)
}

gives

$ go run main.go
Valid JSON, parsed Data: map[:foo age:47 name:map[first:Janet last:Prichard]]

Fetched empty key from GJSON: gjson.Result{Type:3, Raw:"\"foo\"", Str:"foo", Num:0, Index:58, Indexes:[]int(nil)}

New JSON string after SJSON: {"name":{"first":"Janet","last":"Prichard"},"age":47, "": "foo"}
SJSON error: path cannot be empty

Would you consider fixing this limitation?

tidwall commented 6 months ago

I would consider having this limitation lifted. It's been in there since the first commit. I'm not sure why.

vbatanov commented 1 month ago

Is there any plans to fix this? Or there is any other possible way to remove empty key from Json object ?