func main() { const jsonStream = ` {"Name": "Ed", "Text": "Knock knock."} {"Name": "Sam", "Text": "Who's there?"} {"Name": "Ed", "Text": "Go fmt."} {"Name": "Sam", "Text": "Go fmt who?"} {"Name": "Ed", "Text": "Go fmt yourself!"} ` type Message struct { Name, Text string } dec := json.NewDecoder(strings.NewReader(jsonStream)) for { var m Message if err := dec.Decode(&m); err == io.EOF { break } else if err != nil { log.Fatal(err) } fmt.Printf("%s: %s\n", m.Name, m.Text) }}func main() { const jsonStream = `[ {"Name": "Ed", "Text": "Knock knock."}, {"Name": "Sam", "Text": "Who's there?"}, {"Name": "Ed", "Text": "Go fmt."}, {"Name": "Sam", "Text": "Go fmt who?"}, {"Name": "Ed", "Text": "Go fmt yourself!"} ]` type Message struct { Name, Text string } dec := json.NewDecoder(strings.NewReader(jsonStream)) var m []Message for i := 1; ; i++ { if err := dec.Decode(&m); err == io.EOF { break } else if err != nil { log.Fatal(err) } fmt.Printf("row count: %d\n", i) } for _, msg := range m { fmt.Printf("%s: %s\n", msg.Name, msg.Text) }}I don't know if Json has the idea of a row, but looking at the data if you wrote a bufIo.Scanner custom splitter that split between { and } then you could feed each line to json.Unmarshal individually.
Kevin - It's not a matter of goroutines or asynchronous processing. It's a question of the incoming data being objects in an array (like the second example) vs completely separate and unrelated json objects like the first example.
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Just skip the first [ and use the Decoder in a loop on the rest.
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
That actually doesn't work. The Decoder rejects the commas separating the array elements. Also the Decoder reads ahead into its own buffer, so you can't just consume the commas yourself. There was a conversation on this exact subject earlier on this list, and it had some solutions.
On Mon Dec 08 2014 at 11:22:36 PM Tamás Gulácsi <tgula...@gmail.com> wrote:
Just skip the first [ and use the Decoder in a loop on the rest.
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
I have large amounts of JSON arrays that I would like to parse one row at a time.
I thought about it a little more and the code I posted will work fine with all UTF-8.
--