Golang : Count JSON objects and convert to slice/array
Problem :
You have an array of JSON objects and you want to count the number of JSON objects. You also want to convert the JSON objects into slice or array and access the data. How to do that?
NOTE : Useful in situation where you want to know in advance the total number of objects to create a list. Such as the JSON result return by Elastic Search and you want to paginate the result. The list also need some summary information to become something.... like a book index.
Solution :
First convert the JSON objects to type interface{}
and then count the number with len()
function. To access the data. you will have to convert the type interface{}
to map[string]interface{}
Here is an example :
package main
import (
"encoding/json"
"fmt"
"os"
)
var jsonStr = `[
{
"ID1": "Y",
"ID2": 1888,
"ID3": "F",
"ID4": [
{
"Contact Zip": "12345",
"Date of Contact": "08/14/2015"
}
]
},
{
"ID1": "Y",
"ID2": 1889,
"ID3": "M",
"ID4": [
{
"Contact Zip": "12346",
"Date of Contact": "08/13/2015"
}
]
}
]`
func main() {
var jsonObjs interface{}
json.Unmarshal([]byte(jsonStr), &jsonObjs)
// convert the json objects to slice/array of interface{}
objSlice, ok := jsonObjs.([]interface{})
if !ok {
fmt.Println("cannot convert the JSON objects")
os.Exit(1)
}
// count the number of JSON object
fmt.Println("Number of JSON objects : ", len(objSlice))
// iterate the JSON slice
for _, obj := range objSlice {
// convert each obj to map[string]interface{} from interface{}
// because, interface{} alone does not support indexing
objMap, ok := obj.(map[string]interface{})
if !ok {
fmt.Println("cannot convert interface{} to type map[string]interface{}")
}
fmt.Println(objMap)
// now we can access the data with key index
fmt.Println("ID4 : ", objMap["ID4"])
}
}
Output :
Number of JSON objects : 2
map[ID1:Y ID2:1888 ID3:F ID4:[map[Contact Zip:12345 Date of Contact:08/14/2015]]]
ID4 : [map[Date of Contact:08/14/2015 Contact Zip:12345]]
map[ID1:Y ID2:1889 ID3:M ID4:[map[Contact Zip:12346 Date of Contact:08/13/2015]]]
ID4 : [map[Contact Zip:12346 Date of Contact:08/13/2015]]
Play at http://play.golang.org/p/rmNCyyXz5C
Reference :
See also : Golang : Decode/unmarshal unknown JSON data type with map[string]interface
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+8.3k Linux/Unix : fatal: the Postfix mail system is already running
+8.5k Yum Error: no such table: packages
+20.4k Golang : Convert PNG transparent background image to JPG or JPEG image
+10.3k Golang : Interfacing with PayPal's IPN(Instant Payment Notification) example
+27k Golang : Convert CSV data to JSON format and save to file
+19k Golang : Execute shell command
+13.1k Facebook PHP getUser() returns 0
+23.2k Golang : Check if element exist in map
+20.7k Golang : Clean up null characters from input data
+22.7k Golang : Randomly pick an item from a slice/array example
+9.3k Golang : How to generate Code 39 barcode?
+11k Golang : Fix fmt.Scanf() on Windows will scan input twice problem