Is it feasible to model general JSON arrays in a struct using Go?

Is it possible to Marshal/Unmarshal a struct in Go?

type MyType struct {
    Items    <What should be included here?>   `json:"item"`
}

An example JSON document that needs to be handled is

{"items":["value1", {"x":"y"}, "value3"]}

I am new to Go and considering imposing restrictions on the array structure. For instance, transforming the above example into:

{"items":[
    {"type":null, "value":"value1"},
    {"type":"x", "value":"y"},
    {"type":"value3", "value":"value3"}
]}

Alternatively, can I achieve my goal without restructuring the array this way?

Answer №1

It is important that your Items are in the form of an array of interfaces.

Here's an example:

Items []interface{}

For a complete example, check out this link:
http://play.golang.org/p/LOXCiSmUET

When you unmarshal your JSON data and want to iterate over your Items, it's crucial to identify the type. Keep in mind that complex types are represented as map[string]interface and not as a struct. In such cases, you will need to create the struct yourself.

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 integrating dynamic JSON data with Retrofit in Android applications?

My current project involves developing an app that presents daily stock data to the user. However, I am facing a challenge with using retrofit for API calls due to the structure of the JSON response. It seems impractical to create a POJO for each individua ...

Utilizing Node.js to insert and retrieve unprocessed JSON data in MySQL

In my MySQL table, I have a column called jsonvalues with the data type set to blob. I am storing raw JSON values in this field as shown below: {"name":"john","mob":"23434"} However, when I retrieve these values from the database in Node.js, the JSON for ...

Error: Unable to decode productsTest.json file from application bundle

A notification popped up showing "Build Succeeded". However, on the canvas, an error message displayed saying "Could not view this file - crashed". Subsequently, the application crashed. The issue seems to originate from JSONDecoder.sw ...

Symfony's DataTables is encountering an issue with the JSON response, showing

I have encountered an issue while trying to fetch data from a response within my template table (using DataTables). The error message I receive is as follows: DataTables warning: table id=example - Invalid JSON response. For more information about this ...

Using NiFi - Easy steps to send a GET request with JSON using the InvokeHTTP processor

I am attempting to send a GET request with JSON data to https://www.example.com/api/ GET /path/to/data { "abcd": [ "a1", "a2" ] } The URL encoding for this request is as follows: https://www.example.com/api/path/to/data?json=%8B%0B%+..... I ha ...

Unexpected equals sign caused JSON conversion to fail

I'm attempting to create JSON for sending to a webservice. The desired final JSON should appear as follows: { "name": "Pravidlo", "partQualities": [ "A", "O", "N" ], "residualValueMax": 100, "residualValueMin": 0, "selectionSt ...

Methods to Exclude api_key from URL in AngularJS

To make a GET request to a REST API, I require an apikey. The request will be formed like this - $http.get() The response from the API will be in JSON format. However, for security reasons, I don't want the api key to be visible in the URL. Is ther ...

The JSONP request connected to the user input field and button will only trigger a single time

Hello all, I'm new to this and have been searching the internet high and low to see if anyone has encountered a similar issue before, but haven't had any luck. I've been attempting to set up a JSONP request to Wikipedia that is connected to ...

Attempting to concatenate a missing closing curly brace to an invalid JSON entity

There is a json file with a line missing a closing bracket ('}') at the end. Example input: {"title_text": "Malformed JSON", "createdAt": "2020-10-17T02:56:51+0700", "text": "Some post conte ...

Challenges in altering a WAV file using Python

I am currently facing a challenge with rewriting a .wav file, specifically a wave audio file. My project involves the conversion of wave file data into bytes and then reconstructing a new audio file that sounds identical to the original. However, when att ...

Issues with MVC4 JSON Model Binding are causing problems

We have created a Viewmodel named GetUsersFromNextCircuitRequest, which includes the following properties: public class GetUsersFromNextCircuitRequest { public int? dosarId { get; set; } public List<int> dosareIds { get; set; } ...

Error encountered during JSON deserialization. The data type System.Guid is not supported

During my work on an API project, I encountered the following issue: This is the JSON I am passing: { "MainClass": [ { "Text": ".", "Id": { "System.Guid": "06073a9c-9cef-4f07-9180-2e54e0fa6416" } } ] } Here are my C ...

Can graphs be generated in Zabbix using JSON data?

Is it possible to generate JSON code that can be represented on a graph in Zabbix? For example: Let's say we have this JSON data: { "response:" { "success": true, "server": { "name": "Test Server", "alive ...

Transferring JSON data between two .NET REST APIs

Due to certain circumstances I won't elaborate on, we are working with 2 .NET Web APIs (A and B). A website sends JSON data to A via jQuery's .ajax() method, and then A needs to forward it to B. Within A, I have a model being passed as a paramet ...

`Developing data-driven applications with MVC3 using object binding`

Currently, I am facing a challenge with my project that involves using Entity Framework. To provide context on the database model: public class AssetType{ public ICollection<Field> Fields { get; set; } } public class Field{ public int Id {g ...

How to include a key-value pair to a JSON object within an array using JavaScript

I am looking to include the following functionality in the JSON data provided below: "Check if the key name default exists, and if it does, add another key within the same object => ("pin" : 91)." I have attempted to achieve this using the code snippet b ...

Ways to link the output from a dictionary to a class object using C# LINQ

Dictionary<Guid, string> userEventTriggers = RepositoryContainer.GBM.Flex.Admin_UserEventTriggers.AsQueryable() .Where(x => userEventTriggerIds.Contains(x.RecordID)).ToDictionary(x => x.RecordID, x => x.Name); Dict ...

Choose a single value from various iterations

Looking to extract one value from each array in a list and use them to create a JSON structure. Currently, the currency value for every managedstrategy is always the last value in the loop. How can I access the 1st, then 2nd value etc while looping through ...

Obtaining JSON parameters from a URL: A step-by-step guide

Hey there, I recently visited a thread on the topic of obtaining a JSON object from a specific URL. In my attempts, I encountered an issue while trying to access marketCap->usd. If anyone could shed some light on what might be going wrong here, I would g ...

Is there a way to deserialize JSON into an empty struct within a function without losing its type information?

Can someone help me with a question regarding JSON unmarshalling? I am facing an issue where the type is lost after unmarshalling the data. Here's an example of what I'm experiencing: package main import ( "encoding/json" " ...