JSON to dataframes

Hello everyone,

First of all, thanks to those who will take the time to read this post, and help me.

I try to develop a datasource which display informations from a mysql table.
Here is a view of the field I want to process (JSON format string) :

image

With this request, i can display the json in a table :

rows, err := mysql.QueryContext(ctx, "SELECT details FROM table")

frame := data.NewFrame("frameName")
frame.RefID = q.RefID
frame.Fields = append(frame.Fields, data.NewField("details", nil, []string{}))

for rows.Next() {
	var s string
	rows.Scan(&s)
	frame.AppendRow(s)
}

return backend.DataResponse{
	Frames: data.Frames{frame},
	Error:  nil,
}

It works, the JSON is shown in a table with one columns.
.
.
.
.
.
.
.
I want to explode my JSON string to show the different elements in different columns.
So I have created more fileds and used the UnmarshalJSON function, but the principe is the same :

rows, err := mysql.QueryContext(ctx, "SELECT details FROM table")

frame := data.NewFrame("frameName")
frame.RefID = q.RefID

frame.Fields = append(frame.Fields, data.NewField("counter1", nil, []int8{}))
frame.Fields = append(frame.Fields, data.NewField("counter2", nil, []int8{}))
frame.Fields = append(frame.Fields, data.NewField("counter3", nil, []int64{}))

for rows.Next() {
	var s string
	rows.Scan(&s)
	frame.AppendRow(frame.UnmarshalJSON([]byte(s)))
}

return backend.DataResponse{
	Frames: data.Frames{frame},
	Error:  nil,
}

I don’t understand wy it doesn’t work, is my dataframes not in the right format ?
I have “Metric request error” shown in my datasource :

image

Has anyone ever had this problem ?

Thank you for your patience and your help,
Nicolas

Hello again to everyone,

I was stuck on the problem I have described since 3 days… But I find the solution when I create a new topic here :sweat_smile:

Here is the solution :

So I take back the JSON from a SQL request.
I put this object in a struct, and I create 3 fields for the 3 counters

type jsonStruct struct {
	Counter1	int8	`json:"counter1"`
	Counter2	int8	`json:"counter2"`
	Counter3	int64	`json:"counter3"`
}

var e jsonStruct
frame := data.NewFrame("details")
frame.RefID = q.RefID
frame.Fields = append(frame.Fields, data.NewField("1st counter", nil, []int8{}))
frame.Fields = append(frame.Fields, data.NewField("2nd counter", nil, []int8{}))
frame.Fields = append(frame.Fields, data.NewField("3rd counter", nil, []int64{}))

for rows.Next() {
	var s string
	rows.Scan(&s)
	json.Unmarshal([]byte(s), &e)
	frame.AppendRow(e.Counter1, e.Counter2, e.Counter3)
}

return backend.DataResponse{
	Frames: data.Frames{frame},
	Error:  nil,
}

I use a other unmarshalling function : Unmarshal()

This solutions is working perfectly, but I’m sure that it will be more efficient. I will correct that when I will be less beginner :slight_smile:

Have a good day,
Nicolas