Decoding a JSON array in golang

Can you help me understand why golang unmarshalling is returning a nil result for one decoding attempt of a JSON array, but successful in another? I'm confused about what could be causing this difference. Is it a mistake in the code or is it expected behavior?

package main

import "fmt"
import "encoding/json"

type PublicKey struct {
    Id int
    Key string
}

type KeysResponse struct {
    Collection []PublicKey
}

func main() {
    keysBody := []byte(`[{"id": 1,"key": "-"},{"id": 2,"key": "-"},{"id": 3,"key": "-"}]`)
    keys := make([]PublicKey,0)

    json.Unmarshal(keysBody, &keys)//This works
    fmt.Printf("%#v\n", keys)
    response := KeysResponse{}
    json.Unmarshal(keysBody, &response)//This doesn't work
    fmt.Printf("%#v\n", response)

}

http://play.golang.org/p/L9xDG26M8-

Answer №1

It is important to note that the JSON provided does not match the expected structure for the KeysResponse type. The keys should be within a "Collection" property in an object, as shown below:

{
   "Collection": [{"id": 1,"key": "-"},{"id": 2,"key": "-"},{"id": 3,"key": "-"}]
}

If you want to store the data in the KeysResponse type, I suggest utilizing the following code: response := KeysResponse{keys}, right after unmarshalling into keys.

To clarify further, in the correct scenario, the JSON consists of an array of objects. The example JSON above features an object with a single property named Collection, which holds an array of objects defined by the PublicKey type. When handling JSON unmarshalling in Go, it's beneficial to describe the structure using clear language like this, enabling a precise definition of the necessary types and structures.

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

Learn how to create a PHP activity feed that functions like Facebook, and discover the best methods for converting JSON responses into HTML

We are currently working on a website that functions similarly to Facebook, specifically focusing on the activity feed. To load the user's activity feed, we use AJAX to send a request to a PHP file which then processes the logic and returns the values ...

Unpacking a container containing interconnected objects

Creating a command line two-player chess game has been an exciting challenge for me. I've structured it with a class for each type of chess piece and a main board class, which is outlined below: class Board attr_accessor :board, :choice def init ...

Encountering a JSONDecodeError with the message "Expecting value: line 1 column 1 (char 0), I have come across this

Looking for a solution to the JSONDecodeError: Expecting value: line 1 column 1 (char 0) error? Check out the code snippet provided below: from urllib.request import urlopen api_url = "https://samples.openweathermap.org/data/2.5/weatherq=Lon ...

Creating bar charts with Chartjs using dynamic and variable JSON data sources

I am currently working on developing a dynamic bar graph using JSON data that changes based on the applied filter. The objective is to display the TYPE associated with the PERIOD in the graph, but only if it exists. If not, then nothing should be shown. ...

Transforming text into numbers from JSON response with *ngFor in Angular 6

I'm currently attempting to convert certain strings from a JSON response into numbers. For instance, I need to change the zipcode value from "92998-3874" to 92998-3874. While doing this, I came across a helpful resource on Stack Overflow. However, I s ...

PhoneGap and jQuery prove ineffective in fetching json results from Twitter

I've been working on a project to fetch the most recent 50 tweets with a specific hash tag. The project is built for mobile devices using PhoneGap (0.9.6) and jQuery (1.6.1). Below is my code: function retrieveTweets(hash, numOfResults) { var uri ...

Converting a JSON multidimensional array into a Java multidimensional array

Struggling to convert a JSONArray with a complex multi-dimensional String format into a Java multi-dimensional array. Despite numerous attempted solutions, I keep hitting roadblocks. Hoping for some guidance and clarity from the community. Converting it to ...

Accessing Data from the Wikipedia API

After receiving a JSON response with the following structure: { "batchcomplete": "", "query": { "pages": { "97646": { "pageid": 97646, "ns": 0, "title": "Die Hard", "extract": "Die Hard is a 1988 ...

Tips for presenting JSON data retrieved using jQueryWould you like to know how

Is there a way to extract and display the user id from JSON values? I'm trying to access the user id value. $('User_id').observe('blur', function(e) { var txt = $('User_id').value; jQuery.ajax({ type: 'g ...

Learn how to convert JSON text into a list of objects in C# by utilizing the JsonConvert.DeserializeObject method

If I have JSON data presented below with the column names listed once to reduce data size, how can I convert it into a list of C# objects? // JSON { "COLUMNS": [ "id", "country","lastname", "firstname", "email", "category" ], "DATA": ...

Need help fixing a corrupted JSON file that contains escaped single and double quotes?

Challenge I am faced with a sizable JSON file (~700,000 lines, 1.2GB in size) that contains Twitter data which needs preprocessing for both data and network analysis purposes. While collecting the data, an error occurred: instead of using " as a separator ...

Updating the dependencies in package.json is not reflecting the changes

Attempting to run my friend's project on my machine with the angular-cli led me to discover that the dependencies in the package.json were outdated. In an effort to update them, I used the following commands: npm i -g npm-check-updates npm-check-upda ...

Conditionally omit objects during serialization using Jackson

I'm facing a challenge with a class structure in my project. Here's an example: interface IHideable { boolean isHidden(); } class Address implements IHideable { private String city; private String street; private boolean hidden; ...

Mastering the Art of Parsing Complex JSON Data

I received a JSON output that looks like this. Using getjson, I'm trying to extract the datetime and value fields (italicized and bolded) such as [16:35:08,30.579 kbit/s],[16:35:38,23.345 kbit/s]. Is there any solution to achieve this? Thank you. { ...

Traverse a deeply nested JSON array within an Angular controller to extract distinct values

I am currently facing a challenge where I need to iterate through a nested JSON array structured like this: [ { "title": "EPAM", "technologies": [ "PHP", ".net", "Java", "Mobile", "Objective-C", "P ...

Unable to debug json.loads() code using pdb

I am curious to understand the inner workings of converting a JSON string to a Python dictionary using json.loads() For example: import json s = '{"a": 1, "b": 2}' # input json string d = json.loads(s) # output dictionary object To dive de ...

Using Jquery's getJson method, we can easily fetch and retrieve the appropriate JSON string by

I have the following code snippet at the beginning of the JSON url: if(isset($_GET['template']) && $_GET['template']=="blue") { $inifile_path="ctr/subthemes/blue/"; } else { $inifile_path="ctr/subthemes/fresh-n-clean/"; } Addi ...

Comparing the syntax of JSON to the switch statement in JavaScript

I recently came across a fascinating post on discussing an innovative approach to utilizing switch statements in JavaScript. Below, I've included a code snippet that demonstrates this alternative method. However, I'm puzzled as to why the alter ...

I'm looking for the best way to send POST data to an API with Meteor's HTTP package

Here's my current code snippet: HTTP.post("http://httpbin.org/post", {}, function(error, results) { if (results) { console.log(results); } else { console.log(error) } ...

Using a JSON database to implement various user levels in a domain model

Here is the domain model that I believe to be accurate. I am currently attempting to implement this on a JSON database, but I am uncertain if I am headed in the right direction. From my understanding of JSON, there are no inherent relationships between obj ...