Skip to content

Instantly share code, notes, and snippets.

@sugab
Created November 7, 2018 06:58
Show Gist options
  • Save sugab/4fb797d70345986c763451fc875a3b22 to your computer and use it in GitHub Desktop.
Save sugab/4fb797d70345986c763451fc875a3b22 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"os"
)
func readJSONToken(fileName string, filter func(map[string]interface{}) bool) []map[string]interface{} {
file, _ := os.Open(fileName)
defer file.Close()
decoder := json.NewDecoder(file)
filteredData := []map[string]interface{}{}
// Read the array open bracket
decoder.Token()
data := map[string]interface{}{}
for decoder.More() {
decoder.Decode(&data)
if filter(data) {
filteredData = append(filteredData, data)
}
}
return filteredData
}
@FranckVE
Copy link

FranckVE commented Feb 29, 2020

On line 19 'data := map[string]interface{}{}' should be in the loop, otherwise line 24 'filteredData = append(filteredData, data)' keeps appending the same information multiple times (and this information is changed at every loop on line 21 'decoder.Decode(&data)'). So we end up with filteredData containing a slice of N-times the last value of data... Re-instantiating data at the beginning of each loop prevents that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment