Answer the question
In order to leave comments, you need to log in
A structure with a field containing a JSON string. How to get the correct JSON from such a structure?
Good afternoon!
there is a structure
type DetailedReportRow struct {
Id int64 `json:"id"`
Dt *time.Time `json:"dt"`
Phone string `json:"phone"`
TicketSums string `json:"tickets" sql:"type:json"`
PaymentSum float32 `json:"payment_sum"`
PaySystemId float32 `json:"pay_system_id"`
PayStateName string `json:"pay_state_name"`
BusNo string `json:"bus_no"`
}
...
var result []models.DetailedReportRow
...
slq := fmt.Sprintf(`
select
p.id,
p.success_dt as dt,
p.phone,
p.payment_sum,
p.pay_system_id,
ps.name as pay_state_name,
bb.state_number as bus_no,
p.json_data_r::json->>'s' as ticket_sums -- элемент s содержит массив простых объектов вида [{"p": 90}, {"p": 90}]
FROM
pay_payment p
LEFT JOIN pay_state ps on ps.id = p.pay_state_id
LEFT JOIN bus_bus bb on (bb.qr = p.json_data_r::json->>'q')
...
`)
controllers.DB.Raw(slq).Scan(&result)
return result
func (c ManagerAuthApiCtl) BusDetailedReport() revel.Result {
...
stat := repository.Bus().DetailedReport(date, system, fleet)
return c.RenderJSON(JsonResponse{
Success: true,
Data: map[string]interface{}{"stat": stat},
})
}
{
"success": true,
"data": {
"stat": [
{
"id": 185247,
"dt": "2018-10-18T18:36:07Z",
"phone": "0000000000",
"tickets": "[{\"p\": 90}, {\"p\": 90}]",
"payment_sum": 180,
"pay_system_id": 1,
"pay_state_name": "Успешно оплачен",
"bus_no": "157 АТ 01"
},
...
]
}
}
"tickets": "[{\"p\": 90}, {\"p\": 90}]"
"tickets": [{"p": 90}, {"p": 90}]
type DetailedReportRaw struct {
...
TicketSums json.RawMessage `json:"tickets"`
...
}
Answer the question
In order to leave comments, you need to log in
You just need to make the tickets field a string and unmarshal directly from it, casting it to []byte.
result := map[string]int{}
json.Unmarshal([]byte(someStruct.tickets), &result)
It is necessary to throw out these slashes from the string on the client and that's all - str.replace(/\\/g, '');"tickets": "[{"p": 90}, {"p": 90}]",
web searches resulted in json.RawMessage
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question