Skip to content

Cannot delete an empty key from a JSON object #77

@deathiop

Description

@deathiop

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?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions