An appropriate struct to deserialize cereals

Report a typo

Emma has created a Go program that takes as an input a string with a JSON object and saves it to the cerealsJSON variable:

{
  "cereals": [
    {
      "name": "100% Bran",
      "nutritionFacts": {
        "calories": 70,
        "protein": 4,
        "fat": 1,
        "carbo": 5
      },
      "rating": 68.402973
    },
    {
      "name": "100% Natural Bran",
      "nutritionFacts": {
        "calories": 120,
        "protein": 3,
        "fat": 5,
        "carbo": 8
      },
      "rating": 33.983679
    }
  ]
}

Now she wants to decode the above JSON object into a struct, to do this she needs to perform the following steps:

  1. Create the CerealJSONObject struct that can adequately hold the values and follow the structure of the above JSON object
  2. Write the required code to call the json.Unmarshal() function and use it to decode the JSON object stored within cerealsJSON into the cerealsObj variable of the CerealsJSONObject type.
  3. Print the decoded cerealsObj struct using the "%+v" verb.

This problem uses the bufio package to scan the whitespace-separated strings from the standard input and save the above JSON object into the cerealsJSON variable. However, don't be scared! you don't need to know how the bufio package works to solve this task.

Tip: If you are stuck trying to figure out the proper struct to use, you can paste the above JSON object into the JSON-to-Go struct converter!

Sample Input 1:

{"cereals":[{"name":"100% Bran","nutritionFacts":{"calories":70,"protein":4,"fat":1,"carbo":5},"rating":68.402973},{"name":"100% Natural Bran","nutritionFacts":{"calories":120,"protein":3,"fat":5,"carbo":8},"rating":33.983679}]}

Sample Output 1:

{Cereals:[{Name:100% Bran NutritionFacts:{Calories:70 Protein:4 Fat:1 Carbo:5} Rating:68.402973} {Name:100% Natural Bran NutritionFacts:{Calories:120 Protein:3 Fat:5 Carbo:8} Rating:33.983679}]}
Write a program in Go
package main

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

type CerealsJSONObject struct {
Cereals []struct {
? // write the code to finish the struct definition here!
} `json:"cereals"`
}

func main() {
// DO NOT delete! - This block takes as an input the JSON object for the 'cerealsJSON' variable:
scanner := bufio.NewScanner(os.Stdin)
var cerealsJSON string
scanner.Scan()
cerealsJSON = scanner.Text()

var cerealsObj CerealsJSONObject
// Write the required code below to decode the 'cerealsJSON' object into the 'cerealsObj' struct:
err := ?
if err != nil {
log.Fatal(err)
}

// Print the decoded 'cerealsObj' struct below -- do not change the "%+v" verb!
fmt.Printf("%+v", cerealsObj)
}
___

Create a free account to access the full topic