Convert a JSON object containing strings, integers, and arrays into a map

When working with JSON strings, I prefer to use the Decode() function for unmarshalling:

var data Data
decoder := json.NewDecoder(input)
err = decoder.Decode(&data)

The structure of my data is defined as:

type Data map[string]interface{}

An example of my test data looks like this:

{
  "names": [
    "APPLE",
    "BANANA",
    "ORANGE"
  ], 
  "id":1234,
  "action":"fruitSelection"
}

Although the decoding process goes smoothly for numbers and regular strings, when dealing with an array of strings, I encounter the following panic:

panic: interface conversion: interface is []interface {}, not []string

Answer №1

It is not feasible to convert a slice of struct to a slice of interface it implements due to their inherent differences.

You have two options: manually extract elements one by one and store them in a []string, as shown here, or utilize the json package's functionality to decode the data into your desired model format, exemplified here.

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

Creating an Identical Duplicate of a Returned Array in PHP: Mastering Array-Returning Functions

When working with PHP functions that return arrays, I noticed that when assigning the result to a variable like 'user' below, it creates a copy of the array and places it in index [0]. $user = query("SELECT * FROM `users` WHERE id = ?", $_SESSIO ...

You cannot directly convert a JSON Array into a JSON Object on an Android platform

I am facing an issue with populating a spinner from JSON data. I have successfully printed the response in the log cat, but I am unable to fetch it in the Spinner component. Here is the JSON format that I am working with: JSON : [ { "cat_id": ...

Exploring the depths of ASPjson with nested arrays

Utilizing for JSON parsing and writing. I am working with organizational data where each location can have multiple rooms. However, I encounter an error when trying to create rooms within each location item: Object required: 'JSON.data(...)'. ...

Tips for returning JSON data using AJAX

When working with native JS, I am familiar with using AJAX to display the output from PHP/mySql that is not Json Encoded in the element "some_id" like this: <script> function addItem(value) { xmlhttp = new XMLHttpRequest(); xmlhttp.onrea ...

Is it possible to use Ramses to store and search through unstructured data efficiently?

Looking to provide my users with the ability to store unstructured JSON data alongside structured data using an API generated with Ramses. I'm working on making this data searchable and indexed in Elasticsearch. However, I can't seem to find any ...

What is the best way to handle two different types of JSON within a single class?

The following is the structure of a JSON data: [{"trace":{"details":{"date":"[28-02-2016 11:04:26.856573]","type":"[info]","message":"[system done.]"},"context":{"context":[[{"ID":"john dillinger"}]]}}},{"trace":{"details":{"date":"[28-02-2016 11:04:26.85 ...

Filter out all elements in an array except for one from a JSON response using Angular 2

After receiving a JSON response from a server via HTTP GET, the data structure looks like this: { searchType: "search_1", overview: [ "Bed", "BedSheets", "BedLinen", .. ...

Tips for uploading arrays in Node.js´s:1. Use the `

Can someone help me with posting multiple arrays simultaneously? Here is what I am trying to achieve: { name:"John Snow", detail: [ {size: "M", total: 5, color: "red"}, {size: "S", total: 2, color: "bl ...

Having trouble with authenticating and logging in properly, can't seem to figure it out

Currently facing an issue while trying to log in and post my credentials along with the token. I keep receiving the error message: "ValueError: No element found in " Although I have searched on StackOverflow for a solution, I haven't been able to res ...

Converting array keys to numeric in PHPExcel

Hey everyone, I've been working with PHPExcel to extract data from an xls file. The line of code I'm using is: $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true); It's doing the job well, but the array it retur ...

Retrieve the key name that contains a specific value in JSON data

Currently, I am utilizing the JSONAta library to navigate a complex object. My goal is to extract the keys that meet specific conditions. { "properties": { "WTID": { "pattern": "referen ...

Extracting JSON data from the DataFrame for analysis

I have some data stored in a column named 'data' in my dataframe as strings. I am trying to convert this data into JSON format using the command df['data'].to_json('data.json'). However, the output I am getting is showing esca ...

Utilizing Activator.CreateInstance with List<T> while deserializing JSON using DataContractJsonSerializer

Currently, I am in the process of deserializing a JSON string: [{"id":"1"},{"id":"2"},{"id":"3"}] The corresponding class for these items is as follows: [DataContract] public class MyClass { public MyClass() { this._dtcreate = new ...

Determine if a certain value is present in a JSON data structure

Exploring the depths of NodeJS, I am utilizing a JSON Object for user validation. JSON content (users.json): { "users": [{ "fname": "Robert", "lname": "Downey Jr.", "password": "ironman" }, { "fname": "Chris", ...

Converting data from Node.js 6.10 from hexadecimal to base64 and then to UTF-8

I have a code snippet that generates "data" containing a JSON object. My goal is to extract the HEX-value from the Buffer in the data, and then decode it from HEX to BASE64 to UTF8 in order to convert it into a string. Here is the code snippet: console.l ...

Tips on obtaining the header token to prevent XMLHttpRequest in your Flutter app

I am looking to download a JSON file from the following URL: . However, whenever I call the function, I encounter an Error: XMLHttpRequest error. Upon researching, I discovered that adding my API token in the header might resolve this issue. It should be s ...

What is the easiest method for querying one-to-many connections in Django?

Looking for a more efficient way to return a dictionary in JavaScript that includes data from both a Category table and Sub_category table. The desired format is 'Category1': 'Sub_cat1, Sub_cat2, ...'. Any ideas on a better approach? T ...

The system detected a missing Required MultipartFile parameter in the post request

Can anyone explain to me why I am encountering the error mentioned above? I am unable to figure out the reason. Below is my code, please review it and suggest a solution for fixing this error. The objective is to upload multiple files to a specific locatio ...

The error code UnknownError is being generated by the Microsoft Graph API specifically for users with M

Our application utilizes the Microsoft V2.0 OpenID protocol for Single Sign-On (SSO) to allow MSA and AAD users to log in. Here are the scopes used in the authorization URL: openid profile email user.read After obtaining the access token from the token ...

Obtain an array from a PHP API and insert it into a table in a Flutter

I need help with handling an API response and iterating through it using a foreach loop... Here is the API code: $user = ""; $ssn = ''; $return["message"] = ""; $return["success"] = false; $post_ref = ""; $error = ""; $array =[]; if ($error == ...