Get the length of the unstructures json array

have below json below docs = “Records” :[ “{“a”:“770959028”, “b”:“099898”, “c”:“load-generator-span”, “d”:{“random”:”",“randomtext”:"" }}\n", “{“a”:“770959028”, “b”:“099898”, “c”:“load-generator-span”, “d”:{“random”:”",“randomtext”:"" }}\n", “{“a”:“770959028”, “b”:“099898”, “c”:“load-generator-span”, “d”:{“random”:”",“randomtext”:"" }}\n", “{“a”:“770959028”, “b”:“099898”, “c”:“load-generator-span”, “d”:{“random”:”",“randomtext”:"" }}\n"]}

so I have unmarshall the above string using the json.Unmarshal([]byte(docs), &result) result is map like var result map[string]interface{}

now I can get the all the result[Records] but how can get the length of result[Records], the len function doesn’t work on this it gives me error like invalid argument for len. Is there any better function I can use.

As your code isn’t properly formatted, it is hard to say how your actual JSON looks like or to what go value it might be parsed.

Though if you have a map[string]interface{} and know that for a given key, you have a slice of data, then you can get that slice as slice using a type assertion:

var result map[string]interface{}

json.Unmarshall([]byte(jsonInput), &result)

records, ok := result["Records"].([]interface{})
if !ok { panic("Not a slice") }

count := len(records)

thanks a lot.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.