Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON single value parsing

Tags:

json

go

In python you can take a json object and grab a specific item from it without declaring a struct, saving to a struct then obtaining the value like in Go. Is there a package or easier way to store a specific value from json in Go?

python

res = res.json()
return res['results'][0] 

Go

type Quotes struct {
AskPrice string `json:"ask_price"`
}

quote := new(Quotes)
errJson := json.Unmarshal(content, &quote)
if errJson != nil {
    return "nil", fmt.Errorf("cannot read json body: %v", errJson)
}
like image 801
vinniyo Avatar asked Mar 06 '16 01:03

vinniyo


People also ask

What is JSON parsing?

JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON.

How do I allow a single quote in JSON?

The JSON standard requires double quotes and will not accept single quotes, nor will the parser. If you have a simple case with no escaped single quotes in your strings (which would normally be impossible, but this isn't JSON), you can simple str. replace(/'/g, '"') and you should end up with valid JSON.

What is JSON parsing example?

JSON (JavaScript Object Notation) is a straightforward data exchange format to interchange the server's data, and it is a better alternative for XML. This is because JSON is a lightweight and structured language.

Is a single number valid JSON?

JSON can actually take the form of any data type that is valid for inclusion inside JSON, not just arrays or objects. So for example, a single string or number would be valid JSON. Unlike in JavaScript code in which object properties may be unquoted, in JSON only quoted strings may be used as properties.


1 Answers

You can decode into a map[string]interface{} and then get the element by key.

func main() {
    b := []byte(`{"ask_price":"1.0"}`)
    data := make(map[string]interface{})
    err := json.Unmarshal(b, &data)
    if err != nil {
            panic(err)
    }

    if price, ok := data["ask_price"].(string); ok {
        fmt.Println(price)
    } else {
        panic("wrong type")
    }
}

Structs are often preferred as they are more explicit about the type. You only have to declare the fields in the JSON you care about, and you don't need to type assert the values as you would with a map (encoding/json handles that implicitly).

like image 56
elithrar Avatar answered Sep 26 '22 21:09

elithrar