I am trying to return a JSON response something like this:
c.JSON(http.StatusOK, gin.H{"data": resp, "code": http.StatusOK, "status": "success"})
where resp contains data from a db table (struct) which I have converted to JSON.
I need to return the response in data key in this format:
data["result"] = resp
Sample response should look like:
{
"data": {"result" : ["This is a sample response"]}
}
The response can either be an object or a list of objects.
This is in Python format, how do I do this in Go?
You could see it in the source of gin:
type H map[string]interface{}
So you could use(nested gin.H):
c.JSON(http.StatusOK, gin.H{"data":
gin.H{
"result": []string{"This is a sample response"},
},
"code": http.StatusOK,
"status": "success",
})
Related
Is there any way to dynamically include JSON from the request body in the response?
Input Request
{
"id":"1234",
"message":"{\"key\":\"value\"}"
}
Expected Output
{
"status":"CREATED",
"id":"1234",
"message":"{\"key\":\"value\"}"
}
The message and id fields are dynamic and need to be picked from the request.
I have tried the below mapping to dynamically load the response from the request but \" inside message json is converted to "
{
"request": {
"method": "POST",
"urlPath": "/test"
},
"response": {
"status": 200,
"transformers": [
"response-template"
],
"jsonBody": {
"status": "CREATED",
"id": "{{jsonPath request.body '$.id'}}",
"message": "{{jsonPath request.body '$.message'}}"
}
}
}
This returns message as {"key":"value"}.
Even, I have tried changing the mapping to {{{jsonPath request.body '$.message'}}}. But this messes up the whole response json and message value is being returned as "{"key":"value"}" without escape characters.
I'm looking for suggestions to map message dynamically. Thanks in advance.
i have a api response data in this format
{
"channel": [
{
"link": "https://www.foxnews.com",
"title": "FOX News : World ",
"url": "https://global.fncstatic.com/static/orion/styles/img/fox-news/logos/fox-news-desktop.png"
}
],
"opstatus": 0,
"httpStatusCode": 200
}
and want to print the link and title values. how can i do that?
try this
import json
response =.. your json string;
jsonObj = json.loads(response)
print(jsonObj["channel"][0]["link"])
print(jsonObj["channel"][0]["title"])
//or if you have several objects in channel array
for each in jsonObj['channel']:
print each['link']
I try to get dynamic json data from database "cockroach" but I get null value when execute on golang,
Content data type in database is JSONB, here my golang struct,
note: value of Content here are Dynamic Json (every content have different json value).
If you have idea about this please let me know thanks.
type Result struct {
Topic string
MessageType string
Sender string
Content interface{}
}
type SubscriberResponse struct {
Result []*Result
}
and here my golang service
var results []*Result
var subscriberResponse *SubscriberResponse
sql := (`SELECT topic, message_type, sender, content FROM users`)
rs, err := s.db.QueryContext(ctx, sql)
if err == nil {
for rs.Next() {
result := &Result{}
rs.Scan(
&result.Topic,
&result.MessageType,
&result.Sender,
&result.Content)
results = append(results, result)
}
subscriberResponse = &SubscriberResponse{
Result: results,
}
return subscriberResponse, nil
}
return nil, err
and here result of golang service
{
"Result": [
{
"Topic": "a2",
"MessageType": "b2",
"Sender": "c2",
"Content": null
},
{
"Topic": "a3",
"MessageType": "b3",
"Sender": "c3",
"Content": null
}]
}
here additional info result when execute that query on database
databse result
any idea or modification are welcome.
Hi all I am a beginner trying to learn Go. I am trying to get the status of my EC2 instance using AWS SDK with Golang. I was successfully able to get a JSON response for my instance. I am however, having issues trying to parse the JSON response to get the instance state.
The following is how I get the JSON response:
result, err := ec2Svc.DescribeInstanceStatus(input)
where input is of type ec2.DescribeInstanceStatusInput
The following is the JSON response I get:
{
"InstanceStatuses": [
{
"AvailabilityZone": "ap-southeast-2b",
"Events": null,
"InstanceId": "[VALIDIMAGEID]",
"InstanceState": {
"Code": 16,
"Name": "running"
},
"InstanceStatus": {
"Details": [
{
"ImpairedSince": null,
"Name": "reachability",
"Status": "passed"
}
],
"Status": "ok"
},
"OutpostArn": null,
"SystemStatus": {
"Details": [
{
"ImpairedSince": null,
"Name": "reachability",
"Status": "passed"
}
],
"Status": "ok"
}
}
],
"NextToken": null
}
I then parse the result which is of type DescribeInstanceStatusOutput to String and then pass it to the function parseJson where I attempt to parse the JSON.
result, err := ec2Svc.DescribeInstanceStatus(input)
if err != nil {
fmt.Println("Error", err)
} else {
parseJson(result.String())
//fmt.Printf("%v\n", result)
}
func parseJson(ec2StatusDescription string){
//var x string = ec2StatusDescription.String()
//fmt.Print(ec2StatusDescription)
data := []byte(ec2StatusDescription)
var instanceOutputs InstanceOutput
json.Unmarshal(data, &instanceOutputs)
fmt.Print(instanceOutputs.InstanceStatuses[0].InstanceState.Name)
}
type InstanceOutput struct {
InstanceStatuses [] InstanceStatuses
NextToken *string
}
type InstanceStatuses struct {
AvailabilityZone string
Events *string
InstanceId string
InstanceState InstanceState
InstanceStatus InstanceStatus
OutpostArn *string
SystemStatus SystemStatus
}
type InstanceState struct {
Code int
Name string
}
type InstanceStatus struct {
Details [] InstanceDetails
Status string
}
type InstanceDetails struct {
ImpairedSince *string
Name string
Status string
}
type SystemStatus struct {
Details [] InstanceDetails
Status string
}
I am trying to print the instance state but I keep getting index out of range, and this is because the JSON is not being parsed properly. What am i missing here that's causing the json to not parse correctly? Or am I getting it completely wrong in what I'm doing here? Any help would be highly appreciated.
Trying to parse this JSON response and get the id Value
{
"responseStatus": "SUCCESS",
"size": 1,
"start": 0,
"limit": 200,
"documents": [
{
"document": {
"id": 26,
Using this script to parse the response and post the value as an environment variable, for some reason is not retrieving the expected response.
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("id", jsonData.id);
Although it created the id variable in the environment, the value is empty.
Since the id is under an object in the documents array of the response, you should use this
var jsonData = JSON.parse(responseBody);
var id = jsonData.documents[0].document.id;
postman.setEnvironmentVariable("id", id);