-2
[
  {
   "name" : "abc",
   "age" : 10
  },
  {
   "name" : "def",
   "age" : 12
  }
]

So this is my text.json file and it has array of json objects, so what I want to achieve is reading a single object from a file instead of reading whole json object's array using golang. I don't think ioutil.ReadAll() will give me the desired result.

2 Answers2

2

Hope this answers your question. Commented out part is for decoding all the objects one by one and hence you even optimize it such that multiple goroutines can do the decoding concurrently.

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "os"
)

type jsonStore struct {
    Name string
    Age  int
}

func main() {
    file, err := os.Open("text.json")
    if err != nil {
        log.Println("Can't read file")
    }
    defer file.Close()

    // NewDecoder that reads from file (Recommended when handling big files)
    // It doesn't keeps the whole in memory, and hence use less resources
    decoder := json.NewDecoder(file)
    var data jsonStore

    // Reads the array open bracket
    decoder.Token()

    // Decode reads the next JSON-encoded value from its input and stores it
    decoder.Decode(&data)

    // Prints the first single JSON object
    fmt.Printf("Name: %#v, Age: %#v\n", data.Name, data.Age)

    /*
        // If you want to read all the objects one by one
        var dataArr []jsonStore

        // Reads the array open bracket
        decoder.Token()

        // Appends decoded object to dataArr until every object gets parsed
        for decoder.More() {
            decoder.Decode(&data)
            dataArr = append(dataArr, data)
        }
    */
}

Output

Name: "abc", Age: 10
shmsr
  • 3,802
  • 2
  • 18
  • 29
  • Hey! This is for further reading! It'll explain why I did this. https://stackoverflow.com/a/21198571 – shmsr Dec 12 '19 at 06:15
1

You can open the file, and start reading from it using the json.Decoder. The sketch of the code for reading the first element of the array looks like this:

decoder:=json.NewDecoder(f)
t,err:=decoder.Token()
tok, ok:=t.(json.Delim) 
if ok {
   if tok=='[' {
       for decoder.More() {
         decoder.Decode(&oneEntry)
       }
   }
}

You need to add the error handling.

Burak Serdar
  • 46,455
  • 3
  • 40
  • 59