Marshalling Struct vs Map in Golang [closed] - json

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
Which is better in term of performance or best practice when returning result of JSON, using marshalled struct or map. I've seen some codes use map and marshal them to be returned as json, others use marshaled struct to return json response.
Example:
Use struct:
type Response struct {
A int `json:"a"`
B string `json:"b"`
}
r := Response{A:1,B:"1"}
resp, _ := json.Marshal(r)
Use map:
m := map[string]interface{}{
A: 1,
B: "1",
}
resp, _ := json.Marshal(m)
Which is better?

My though is that using Struct is better since the types of the fields are defined. If you use map then it's obviously you'll use map[string]interface{} since the values will vary. Using interfaces typed data will allocate heap memories. Since you're just returning response then it's better to use struct with defined types to reduce run time checking for the types. The performance difference is not significance tho.

Related

Is encoding/json Marshal a JSON alphabetically by default? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 months ago.
Improve this question
func sort(input string) string {
var data interface{}
_ = json.Unmarshal([]byte(input), &data)
ret, _ := json.Marshal(data)
return string(ret)
}
just like code above, if i Unmarshal a json string into interface, then Marshal it to json string, is this json ret sort by alphabetically default?
seems like encoding/json Marshal will sort keys by alphabetically default, but is there any doc or article prove this?
thanks
According to the functions documentation:
Map values encode as JSON objects. The map's key type must either be a string, an integer type, or implement encoding.TextMarshaler. The map keys are sorted and used as JSON object keys by applying the following rules, subject to the UTF-8 coercion described for string values above:
keys of any string type are used directly
encoding.TextMarshalers are marshaled
integer keys are converted to strings

Unmarshalling nested json with multiple type [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
[
1618511472,
"on-req",
null,
null,
[
[
62577595747,
]
],
]
Above is the json response that needs to be parsed
I'm currently using var resp []interface{} and json.Unmarshal for the raw response. It works for other fields except the array field
When I try to cast the array field resp[4].([][]interface{}) it doesn't work
Not sure what is the best approach here. Appreciate any help. Thanks beforehand
Thanks to mkopriva's answer
This is the working solution
tmp, ok := resp[4].([]interface{})
tmp1, ok1 := tmp.([]interface{})

Encode json array to client [duplicate]

This question already has answers here:
MarshalJSON without having all objects in memory at once
(2 answers)
Closed 2 years ago.
I have the opposite problem as this question.
Decode large stream JSON
In that question, the user asks about decoding a large incoming JSON array.
But, how would I encode a large outgoing JSON array?
For example, I have a http.Handler like this.
enc := json.NewEncoder(resp)
for obj := range objectChannel {
enc.Encode(obj)
}
However, this doesn't work because it ends up sending invalid JSON to the JavaScript client.
Do I have to manually fix the syntax? For example:
enc := json.NewEncoder(resp)
fmt.Fprint(resp, "[")
for obj := range objectChannel {
enc.Encode(obj)
fmt.Fprint(resp, ",") // and account for the last item
}
fmt.Fprint(resp, "]")
Or is there a better way?
If you already have all the objects in memory, there is no point in encoding elements one by one, and you can do:
enc.Encode(lotsOfObjs)
If you get objects one by one, then manually adding [ and ] with commas in between is fine.

How to validate two JSON objects present in a string [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have a JSON String to validate which contains two separate objects. The string is "1A" but i want to validate it as individual objects for example: {"NumberInt":1,"LetterThing":"A"}.
In conclusion, my string is "1A" but I need to validate it as individual objects despite the fact it's in a string format.
Why do I want this? I have a minimum and maximum for the NumberInt integer value and I have a particular pattern for the LetterThing string value. For example: I do not want "5H" to validate.
If this is possible in a string format please let me know how.
Solved:
Was solved by using regex to validate on my JsonSchema i.e "pattern": "^[A-Ja-j1-4\\s]*$".
Thanks guys
You could use a regex to extract what you need from the JSON.
//obtains the number part, then you can perform operations on that number
var startingDigits = incomingString.replace( /^\D+/g, '');
You would need to PARSE the string in this case.
To parse a STRING you ITERATE over each CHARACTER in the string and then compose the needed parsed ELEMENTS.
For example in this CASE you might start looking for only DIGITS and putting them in another string. When you hit a LETTER you can CONVERT that string to an integer.
Then take the REMAINING as the 2nd part.
Finally do your VALIDATION.

Pass String with Json data to Map in Golang [duplicate]

This question already has answers here:
Golang parse JSON array into data structure
(3 answers)
Closed 5 years ago.
Currently I have stored in my database json objects as string. I want to pass them to a map to be able to consult any field as:
Mymap["Name"]
Mymap["Age"]
..
Let's say that my string would be something like:
'{"Name":["zero"],"Age":"10"}'
I don't know the structure of the data, so that Json can have many fields as required and also many levels of nestings (but I am worried more about to get at least the first level)
If you're dealing with a json object of arbitrary structure you can use a map of interfaces as the type to unmarshal it into.
map[string]interface{}
The encoding/json package will nicely unmarshal the json object into it, nested or not.
This, while very flexible, has an obvious downside, the types of the map's values are unknown and so to do anything useful with them you'll have to use a type assertion or type switch.
v, ok := m["key"].(Type)
https://play.golang.org/p/wM0gkU1g5G