Extracting a deeply nested JSON array from a document

After finding a JSON file named sample.json, I discovered that it contains an array of JSON objects with timestamps, extra data IDs, and event information. Here's a snippet:

[
{
  "time": "2021-01-04T00:11:32.362Z",
  "extra_data": {
    "id": "123"
  },
  "info": "event123"
},
{
  "time": "2021-01-05T00:11:32.362Z",
  "extra_data": {
    "id": "456"
  },
  "info": "event456"
},
{
  "time": "2021-01-06T00:11:32.362Z",
  "extra_data": {
    "id": "789"
  },
  "info": "event789"
}
]

To unmarshal this JSON array effectively, allowing access to the ID and info for each event, I have crafted the following solution:

func main() {

    file, err := ioutil.ReadFile("/Users/janedoe/Downloads/sample.json")
    var events Event
    json.Unmarshal([]byte(file), &events)
    fmt.Println(reflect.TypeOf(events))
    // Accessing values by keys for each event
    fmt.Println("Event123_Time :", events.Timestamp,
            "\nEvent123_ExtraData_Id :", events.ExtraData.Id,
            "\nEvent123_Info :", events.Info)
} 
type Event struct {
    Time string `json:"time"`
    ExtraData ExtraData `json:"extra_data"`
    Info string `json:"info"`
}

type ExtraData struct {
     Id string   `json:"id"`
}

The current output does not display any values, indicating an issue with the marshalling process. How can I rectify this?

Answer №1

For working with a JSON array, you should declare the variable as an array too:

var events []Event

Instead of just declaring it as a single Event like this:

var events Event

Below is an updated version incorporating this change:

func main() {
    file, err := ioutil.ReadFile("/Users/janedoe/Downloads/sample.json")
    if err != nil {
        panic(err)
    }
    var events []Event
    if err := json.Unmarshal([]byte(file), &events); err != nil {
        panic(err)
    }
    fmt.Println(reflect.TypeOf(events))
    for i, event := range events {
        // Accessing values by keys for each event
        fmt.Println(i, "Event123_Time :", event.Time,
            "\nEvent123_ExtraData_Id :", event.ExtraData.Id,
            "\nEvent123_Info :", event.Info)
    }
}

type Event struct {
    Time      string    `json:"time"`
    ExtraData ExtraData `json:"extra_data"`
    Info      string    `json:"info"`
}

type ExtraData struct {
    Id string `json:"id"`
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the use of JSON serializers and different HTTP responses in Django

I am currently working on implementing a filter system triggered by a click event, using an AJAX post method to update the content displayed on the template. At this moment, I have been utilizing: return HttpResponse(json.dumps(context), content_type="ap ...

Using Node.js to serialize JSON POST data as an array

Looking to retrieve POST data from my front-end form. Upon using console.log(req.body), I receive the following output: [ { name: 'name', value: 'kevin' } { name: 'email', value: '' }, { name: 'phone' ...

What is causing json_decode to not work on this specific json object?

I've been working on a PHP script that receives a JSON object from http://www.reddit.com/search.json via an HTTP GET request. After some testing, I can confirm that the script successfully retrieves the JSON object. However, when I try to use json_dec ...

Having trouble with the Google Places API integration using Python

Hey there! I'm currently experimenting with the Google Places API in a rather unique way - trying to fetch a list of all McDonald's locations in Germany. I know, it's a bit unusual! Below is the code I've put together for this task (the ...

A guide on leveraging Jackson for validating duplicate properties

Working with the Jackson JSON library to convert JSON objects into POJO classes has brought up an issue. Specifically, when encountering JSON Objects with duplicate properties: { "name":"xiaopang", "email":"<a href="/cdn-cgi/l/email-protection" cla ...

Extracting and storing a dynamically changing JSON file into a dictionary using Python

I am working with a dynamically changing json file, specifically at one point that changes unpredictably. My goal is to iterate through this changing section using a for loop in order to extract the necessary elements within that bracket of the json file. ...

What is the best way to indicate the type of a JSON value?

Currently, I am utilizing Grape on Padrino to develop a test API specifically for my mobile application. I am curious about how I can precisely define the data type of my JSON object. Below is an example of how I am attempting to achieve this, however, e ...

What is the best way to eliminate a specific character from the key of an array of objects using JavaScript?

My JavaScript object looks like this: result = [ {"Account_ID__r.Name":"Yahoo Inc Taiwan","Contact_ID__r.Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="42283427302c2d2e2602362a27313 ...

I'm confused as to why I am only receiving one object entry in my fetch response instead of the expected list of entries

Is there a way to fetch all entries as a response instead of just one value? For example, when the next value returned by the fetch is {"next":"/heretagium"}, I can replace "/hustengium" with "heretagium" to get th ...

What is the best way to utilize React JS for mapping?

How do we navigate through nested objects in ReactJS? { "Data1":{ "attribute1":{ "key":"discount", "value":"50% off" }, "attribute2":{ &qu ...

Utilizing Jayway Implementation for Grouping Predicates in JSON Path

Trying to utilize JSONpath for querying my JSON Object. The logical || or && operator is functioning correctly individually. However, when attempting to group predicates together and then perform the logical || or && operations, it appears not to be workin ...

Using the Ruby programming language, send JSON data using Curl Multi

I am currently implementing a Curl Multi post using JSON data with the help of the curb gem. Unfortunately, I am facing issues with getting the parameters to be properly posted. I have been struggling to configure the parameters correctly despite multiple ...

Develop a JSON ping that returns either a true or false response

Currently, I am utilizing Node-RED with the "node-red-node-ping" to ping the IP address 192.168.0.71. The response received is structured as follows: 192.168.0.71 : msg : Object object payload: 0.376 topic: "192.168.0.71" _msgid: "f766d646.764dc8" In cas ...

Exploring Perl's Json Array capabilities

I am facing an issue with loading an array of JSON objects from a file into Perl. Despite my best efforts, Perl seems to be treating the array as a single object rather than individual items. Any advice or assistance on how to properly handle this would ...

In WPF/C# programming with Newtonsoft, it is necessary to establish a condition using if/else statements before modifying a .json file based on true/false

As a novice navigating a WPF application, I am faced with the task of updating specific values in an external JSON file. These values are restricted to only "true" and "false" outcomes. { "option1": false, "option2": false, " ...

Values from an authorized content provider that are non-primitive are not displaying any data

Utilizing the /v2/registrations endpoint to enroll a content provider with the setting of the legacyForwarding flag. Hence, my Content Provider is showcasing the v1/queryContext endpoint. Whenever I am serving a basic value (Integer, String etc.) like a t ...

Issue with using Javascript variables within Highcharts

I am facing an issue with displaying a high charts pie chart dynamically. When I pass the exact value format into the data index in the high chart, it doesn't show anything in the chart. However, if I directly assign a value to a variable, it works fi ...

Having trouble generating a correct URL in PHP due to concatenation with a variable

I'm encountering an issue when trying to combine a variable and a string to create a URL that will be used in constructing a JSON object. Even though I am receiving a valid JSON response from the Wordreference API, it seems that there may be an error ...

The ng-repeat-start feature is not functioning properly across different levels

I am attempting to utilize the ng-repeat-start directive in order to construct a table that resembles the following: The structure of my JSON data is as follows: [ { "name": "Chapter 1", "parts": [ { "text": "Lorem ipsum... 1", ...

Parsing IcoMoon JSON in PHP

Using css classes, IcoMoon is able to generate font icons along with a JSON file. Currently, I am working on a PHP project where I need to iterate through their JSON font file in order to extract all the font names. { "IcoMoonType": "selection", " ...