The property differs when being read from the input stream

This snippet of code is used to test the functionality of listing users in a web application.

    req := httptest.NewRequest("GET", "/v1/users", nil)
    resp := httptest.NewRecorder()

    u.app.ServeHTTP(resp, req)

    if resp.Code != http.StatusOK {
        t.Fatalf("getting users: expected status code %v, got %v", http.StatusOK, resp.Code)
    }

    var list []map[string]interface{}
    if err := json.NewDecoder(resp.Body).Decode(&list); err != nil {
        t.Fatalf("decoding users: %s", err)
    }

    want := []map[string]interface{}{
        {
            "id":           "a2b0639f-2cc6-44b8-b97b-15d69dbb511e",
            "name":         "dcc",
            "role_id":      float64(101),
            "date_created": "2019-01-01T00:00:01Z",
            "date_updated": "2019-01-01T00:00:01Z",
        },
    }

The role_id is supposed to be an integer type according to the model definition.

type User struct {
    ID          string    `db:"user_id" json:"id"`
    UserName    string    `db:"user_name" json:"user_name"`
    RoleID      int       `db:"role_id" json:"role_id"`
    DateCreated time.Time `db:"date_created" json:"date_created"`
    DateUpdated time.Time `db:"date_updated" json:"date_updated"`
}

However, it appears that the role_id is being converted to a float64 when inputting it to the stream. This inconsistency should be investigated further.

Answer №1

User.RoleID is of integer type and will be encoded as a JSON Number. When unmarshaling into a value of type map[string]interface{}, which has an interface value type, the float64 type is selected for unmarshaling.

As stated in the json.Unmarshal() documentation:

To unmarshal JSON into an interface value, Unmarshal stores one of these types in the interface value:

bool for JSON booleans
float64 for JSON numbers
string for JSON strings
[]interface{} for JSON arrays
map[string]interface{} for JSON objects
nil for JSON null 

If you are aware that the response contains a User object, then unmarshal it into a value of type User.

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

Generate JSON data and transmit it to the server utilizing Objective C

I'm having issues with sending JSON data to the server side using the POST method in my Objective C code. Despite fetching data from text fields and converting it into a string, when I try to convert this value into a JSON object, it returns null. I&a ...

ajax request fetching new data upon webpage reload

I'm encountering an issue where a JSON jQuery call only works when the page is refreshed after loading. Meaning, on initial page load, the data is not updated, but upon refreshing the page, the data is refreshed successfully. This data feeds into a se ...

Locate and retrieve all the records that contain an asterisk symbol in MongoDB

Could someone provide assistance with finding documents in MongoDB that contain the '*' character using regex? For example, the following regex (db.collection.find{value: new Regex('*')}) should retrieve all documents with '*&apos ...

Struggling to access specific data within a JSON object? Wondering how to extract and display data from a JSON object in VUE?

Despite my extensive searching on Stack and the internet, I have not been able to find a solution to my problem. Currently, I am attempting to retrieve data from a JSON file located in the Vue src folder. The file contains three arrays with names that inc ...

Error: Found an unconventional token "e" in JSON data at position 1 during parsing in JSON.parse function

Is there a way to retrieve a string value by calling an API in Angular? Here is my approach: Service file - public getRespondDashboardUrl(): Observable<any> { return this.http.get(`ref/RespondDashboardUrl`); } Component File respondDashboar ...

Position of JSON data response is inaccurate

Currently, I have a function that calls an API from the server in the following manner: getDataSet(callback) { request.open('POST', `${apiPath}`); request.setRequestHeader('Content-Type', 'application/x-ww ...

Manipulating data using jquery to organize the structure of an HTML document

I am in the process of parsing this JSON data and extracting all the information from it. I am not very experienced with parsing JSON, so any help would be greatly appreciated. http://jsfiddle.net/NJMyD/1044/ html <div class="items"> <di ...

Using iOS to send a request - Receiving a response with a 304 HTTP status code from

I am currently in the process of developing an application specifically designed for iPad users. To create this app, I am utilizing Express and a restful approach as the backend framework. The code snippet below demonstrates how Express should respond on t ...

Utilizing JSON parse/stringify for data manipulation

I'm seeking advice on manipulating JSON data using JavaScript, particularly with the stringify/parse methods. In this scenario, I start by creating a JSON string and then use parse to convert it into an object. However, my goal is to efficiently delet ...

Converting a JSONObject to an Array in JavaScript

I am new to JSON and encountering an error while trying to fetch data: E/Volley: com.android.volley.ParseError: org.json.JSONException: Edit: Full StackTrace: 2020-11-10 20:06:48.606 10505-10505/com.madcoderz.jsonparsing E/Volley: com.android.volley.Pars ...

What sets apart WordPress REST API from WP JSON API?

I'm currently developing an authentication feature for my app using API. I'm having difficulty deciding between utilizing the WordPress REST API or the WordPress JSON API. Reading through this Q&A thread, it suggests that I should opt for the ...

Tips for inserting information from a JSON file into a mailto hyperlink

As a newcomer to JavaScript, I am eager to tackle the challenge presented below: Situation: In possession of a JSON file containing personal details such as name, email address, bio, etc., my task is to design a basic web page showcasing this data for ea ...

How can I verify the status of an occasional undefined JSON value?

There are times when the JSON object I'm trying to access does not exist. Error: Undefined index: movies in C:\xampp\htdocs\example\game.php In game.php, I'm attempting to retrieve it from the Steam API using this code: $ ...

Having difficulty pushing JSON elements into an array

I am currently working on serializing a GET request to create movie objects, which are then appended to a movies array that will be utilized to display information on the UI. As a newcomer, I have been struggling with this issue for quite some time now :( ...

Determine the attribute by assigning a value to @JsonProperty when using the object mapper

Currently, I am working with Spring and Hibernate in my project. One of the challenges I encounter is dealing with a DTO class that has multiple string member variables. The goal is to enable users to search for objects based on any field within this class ...

Guide on transforming JSON lines that have been escaped into a collection of beans

Java POJO: import android.os.Parcel; import android.os.Parcelable; import com.gongzelong.duolingowordsearch.utils.ParcelableUtils; import com.google.gson.annotations.SerializedName; import java.util.List; public class WordSearch implements Parcelable ...

What is the best way to transform JSON into a Swift Dictionary so that it can be used for an HTTP POST

I'm encountering difficulties in organizing my JSON data into a Swift dictionary to send as the HTTP body through an API. This is the structure of my JSON: { "idNo": "string", "name": "string", "isRe ...

Separate the keys and values of a JSON file into individual rows within a pandas dataframe

Looking to extract keys and values from JSON into separate rows in pandas The current structure is: |---------------------|------------------| | session | scoring | |---------------------|------------------| | session1 | {i ...

How can I make a Java API request using JsonReader?

Having trouble figuring this out: I need to call the openweather api in java and display the result on the console. Can't seem to find any helpful tutorials, they all focus on parsing JSON from a file... Not sure if I'm on the right track? Tryin ...

What is the best way to extract the lodash score from a URL using JSON parsing?

Can someone help me figure out how to extract and store the names from a URL into an array, then parse JSON data to retrieve the lodash score and convert it into a whole number? Any assistance would be greatly appreciated. <head> <title> ...