Jeffail/gabs

Why does String() return a value wrapped in quotes?

Closed this issue · 2 comments

I've been hitting this recently and finding it really weird!

I would expect String() to return a string containing the value, but it seems to include the containing quotes. For example, I would expect this to output "Matches":

package main

import (
    "fmt"

    "github.com/jeffail/gabs"
)

func main() {
    jsonParsed, _ := gabs.ParseJSON([]byte(`{
    "test":{
      "key": "value"
    }
  }`))

    if jsonParsed.Path("test.key").String() == "value" {
        fmt.Println("Matches")
    } else {
        fmt.Println("Doesn't match")
    }
}

On the other hand this works fine, but String() should work from a new user to the library point of view:

if jsonParsed.Path("test.key").Data() == "value" {
    fmt.Println("Matches")
} else {
    fmt.Println("Doesn't match")
}

Hey @andyjeffries , this is because calling .String() on a *Container type will print the JSON encoding of whatever data is contained within. In this case your data happens to be a string, but for the purposes of JSON encoding I believe it's correct to print the value within quotes.

The correct way to extract the underlying string in this case would be jsonParsed.Path("test.key").Data().(string). I know that's more verbose and less ideal but it's more in line with typical Go customs and saves me writing a page of boilerplate for supporting all data types.

You are right that the name is misleading, from the beginning this probably should have been named .JSONString(), but to change it now would be a breaking change, so although I feel your pain I'd rather leave it as is.

OK mate, I understand. I'll close this issue, but hopefully at least by it being here - I did an Issues search first - then others won't be caught by the trap. I did have a look at the README.md to see if there was an easy way of making it clear with a clarification there, but not easily with the current content.