Guide to decoding a list of interface types from JSON in Golang

In my code, there's a package called variables which contains an interface Variable, and two structs that implement the methods in the interface - NumericalVariable and TextualVariable. Here is how they are structured...

package variables

type Variable interface {
    GetColumnIndex() int
    IsActive() bool
    StartDataLoad()
    AddData(value string) (bool, error)
    FinishDataLoad()
    VectorLength() int
    SetVectorOffset(offset int)
    LoadIntoVector(sv string, vector []float64) float64
}

type NumericVariable struct {
    Column_idx    int
    Name          string
    Vector_offset int
    Mean          float64
    Sum           float64
    SumSq         float64
    SD            float64
    Count         float64
    Max           float64
    Min           float64
    Vector_max    float64
    Vector_min    float64
    values        []float64
    Active        bool
}

type Category struct {
    Count         int
    Vector_offset int
    Coefficient   float64
}

type TextualVariable struct {
    Column_idx    int
    Name          string
    Vector_offset int
    Categories    map[string]Category
    Categories_k  float64
    Active        bool
    Count         int
}

Additionally, I have another module named model which defines a type Model containing a slice of Variable interfaces, as shown below...

package model

type Model struct {
    Vars []variables.Variable
}

During data processing, I instantiate either a NumericalVariable or TextualVariable based on the data at hand, adding these instances to the Vars slice within a Model object. My goal is to be able to save and load the Model struct from a JSON file.

While saving is straightforward thanks to Golang's json package, reading poses a challenge due to model.Vars being a slice of interfaces without explicit type information during unmarshalling.

To tackle this issue, reflection seemed like a viable solution but has me stumped in implementation. Here's a snippet of what I've tried...

func (_self Model) Read(filename string) {
    _model, err := ioutil.ReadFile(filename)
    if err != nil {
        log.Fatal(err)
        return
    }

    var dat map[string][]interface{}
    err = json.Unmarshal([]byte(_model), &dat)
    if err != nil {
        log.Fatal(err)
        return
    }
    _vars := dat["Vars"]
    for _, _vi := range _vars {
        k := reflect.ValueOf(_vi)
        if k.Kind() == reflect.Map {
            if len(k.MapKeys()) == 13 {
                // This is a numeric variable
                nv := variables.NumericVariable()
                // How do I proceed to load values into nv using reflection?
            }
            if len(k.MapKeys()) == 8 {
                // This is a textual variable
                tv := variables.TextualVariable()
                // Similarly, how can I utilize reflection to populate tv with the reflected values?
            }
        }
    }

I am able to detect the types correctly through reflection, but struggle with loading the values into their respective structs automatically. Any guidance on effectively utilizing reflection for automatic unmarshalling would be greatly appreciated.

Answer №1

Transform your map[string]interface{} directly into a struct by utilizing type assertion to extract values from the map.


var nv NumericVariable 

for key, value := range vars {
   nv.Column_idx = vars[key].(int) // Convert interface{} to int
   nv.Name = vars[key].(string) // Convert interface{} to string
   ..
   ..
}


Using type assertion to convert interface values from a map to your specified type in the struct.

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

Tips for accurately determining the count, rather than the character length, of JSON data

After running my code, I believe it returns a JSON array. The resulting JSON array is then stored in a JavaScript variable called 'result'. When I console.log(result); in Firefox, the output shown is: [{"id":"G24","value":"Zas, S"},{"id":"G75" ...

Converting objects into JSON format

I'm trying to transform an object that looks like this: { user[id]: 1, user[name]: 'Lorem', money: '15.00' } Into the following structure: { user: { id: 1, name: 'Lorem', }, money: ...

Leverage recursion for code optimization

I'm currently working on optimizing a function that retrieves JSON data stored in localStorage using dot notation. The get() function provided below is functional, but it feels verbose and limited in its current state. I believe there's room for ...

use the fetch api to send a url variable

I'm struggling to pass a URL variable through the API fetch and I can't seem to retrieve any results. As a newcomer to Javascript, any help is greatly appreciated. //Get IP address fetch('https://extreme-ip-lookup.com/json/') .then(( ...

Defining JSON Schema for an array containing tuples

Any assistance is greatly appreciated. I'm a newcomer to JSON and JSON schema. I attempted to create a JSON schema for an array of tuples but it's not validating multiple records like a loop for all similar types of tuples. Below is a JSON sampl ...

Transforming API Response into a structured format to showcase a well-organized list

When I make an API call for a list of properties, the data comes back unorganized. Here is how the data from the API looks when stored in vuex: posts:[ { id: 1; title: "Place", acf: { address: { state: "Arkansas", ...

What is the process for displaying node_modules directories in a json/javascript document?

Exploring ways to showcase the dependencies within my d3.js tree, I am curious if it's possible to dynamically list the dependencies' names in a JSON file or directly within the javascript file. I'm puzzled by how JavaScript can access folde ...

Ng-repeat seems to be having trouble showing the JSON data

Thank you in advance for any assistance. I have a factory in my application that utilizes a post method to retrieve data from a C# function. Despite successfully receiving the data and logging it to the console, I am facing difficulties in properly display ...

Fetching data using JSONRequest sample code

I am new to web development and this is my first attempt at using JSON. On the JSON website (http://www.json.org/JSONRequest.html), they recommend using JSONRequest.get for certain tasks. However, I keep running into an error stating "JSONRequest is not ...

What is the best method for encoding non-ASCII characters in JSON.stringify as ASCII-safe escaped characters (uXXXX) without the need for additional post-processing?

In order to send characters like ü to the server as unicode characters but in an ASCII-safe string format, I need them to be represented as \u00fc with 6 characters, rather than displaying the character itself. However, no matter what I try, after us ...

Utilizing JSON for Google Charts

Although I have no prior experience with Google Charts, I am currently attempting to graph temperature data collected from sensors placed around my house. Unfortunately, I keep encountering an Exception error. I suspect the issue lies in the JSON format no ...

trouble encountered while parsing JSON information using JavaScript

[ [ { "Id": 1234, "PersonId": 1, "Message": "hiii", "Image": "5_201309091104109.jpg", "Likes": 7, "Status": 1, "OtherId": 3, "Friends": 0 } ], [ { "Id": 201309091100159, "PersonI ...

Using JavaScript to transform JSON information into Excel format

I have tried various solutions to my problem, but none seem to fit my specific requirement. Let me walk you through what I have attempted. function JSONToCSVConvertor(JSONData, ReportTitle, ShowLabel) { //If JSONData is not an object then JSON.parse will ...

Customizing response headers in vanilla Node.js

My Node.js setup involves the following flow: Client --> Node.js --> External Rest API The reverse response flow is required. To meet this requirement, I am tasked with capturing response headers from the External Rest API and appending them to Nod ...

Ensure the page is always updated by automatically refreshing it with JavaScript each time it

I'm currently working on a web application that makes use of JQuery. Within my javascript code, there's a function triggered by an onclick event in the HTML which executes this line: $('#secondPage').load('pages/calendar.html&apos ...

Passing a Value from Child to Parent Function in Meteor: A Complete Guide

I am trying to pass the value of a result from a child element to its parent element. Initially, I used Session.set and Session.get which worked fine but I realize that using Sessions globally is not considered good practice. So, I attempted to utilize rea ...

Update JSON data in ng-blur event using AngularJS

Could you offer some guidance on how to push the content from a text box into JSON when I click outside of the box? Below is the code for my text box: <input type="text" name="treatmentCost" class="form-control" ng-model="addTemplate" /> And here i ...

Removing the column name from a JSON return in C# involves using a variety of techniques

Below is a JSON output I have received : [ { positionCode: "POS1", positionName: "POSITION 1", positionDescription: "", parentPosition: "POS2", }, { positionCode: "POS2", positionName: "POSITION ...

Efficient ways to organize JSON objects using JavaScript

I am in need of restructuring the data retrieved from an API call, which currently looks like this: { "Label3": [ { "name": "superman", "power": 8900 }, { "name": "iron man", "power": 3000 }, { "name": "spike spiegal", "power": 200 ...

Eliminate duplicate items using the reduce method in JavaScript

Working with a set of Json Objects, I use a javascript map function to list each field along with an array of its possible types. For example: birthDate, [Date, String, String, String, String] isMarried, [Boolean, Boolean, Boolean, Boolean, String] name, ...