5

Using Python I can do following:

r = requests.get(url_base + url)
jsonObj = json.loads(r.content.decode('raw_unicode_escape'))
print(jsonObj["PartDetails"]["ManufacturerPartNumber"]

Is there any way to perform same thing using Golang? Currently I need following:

json.Unmarshal(body, &part_number_json)
fmt.Println("\r\nPartDetails: ", part_number_json.(map[string]interface{})["PartDetails"].(map[string]interface{})["ManufacturerPartNumber"])

That is to say I need to use casting for each field of JSON what tires and makes the code unreadable. I tried this using reflection but it is not comphortable too.

EDIT: currently use following function:

func jso(json interface{}, fields ...string) interface{} {
    res := json
    for _, v := range fields {
        res = res.(map[string]interface{})[v]
    }
    return res
}

and call it like that:

fmt.Println("PartDetails: ", jso( part_number_json, "PartDetails", "ManufacturerPartNumber") )
0

2 Answers 2

11

There are third-party packages like gjson that can help you do that.

That said, note that Go is Go, and Python is Python. Go is statically typed, for better and worse. It takes more code to write simple JSON manipulation, but that code should be easier to maintain later since it's more strictly typed and the compiler helps you check against error. Types also serve as documentation - simply nesting dicts and arrays is completely arbitrary.

Sign up to request clarification or add additional context in comments.

Comments

2

I have found the following resource very helpful in creating a struct from json. Unmarshaling should only match the fields you have defined in the struct, so take what you need, and leave the rest if you like.

https://mholt.github.io/json-to-go/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.