How to parse json object and print particular value [duplicate] - arrays

This question already has answers here:
JSON single value parsing
(2 answers)
Closed 2 years ago.
I have json object that consists sub object of array. how can I print particular sub object in json.
here is my code
package main
import (
"encoding/json"
"fmt"
)
func main() {
//Simple Employee JSON which we will parse
empArray := `{"meta":[
{
"id": 1,
"name": "Mr. Boss",
"department": "",
"designation": "Director"
},
{
"id": 11,
"name": "Irshad",
"department": "IT",
"designation": "Product Manager"
},
{
"id": 12,
"name": "Pankaj",
"department": "IT",
"designation": "Team Lead"
}
]}`
// Declared an empty interface of type Array
var results []map[string]interface{}
// Unmarshal or Decode the JSON to the interface.
json.Unmarshal([]byte(empArray['meta']), &results)
fmt.Println(results)
}
I'm getting below error while doing soo..
./test.go:35:23: cannot convert empArray['\u0000'] (type byte) to type []byte
./test.go:35:33: invalid character literal (more than one character)
with in the empArray array object, I wanted to print meta object that consists array of employees. Please help me to accomplish this.

You are almost there. Parse the entire document and then pick out the part you want.
var results map[string][]interface{}
json.Unmarshal([]byte(empArray), &results)
fmt.Println(results["meta"])

You should use custom structs:
type Employee struct {
ID int `json:"id"`
Name string `json:"name"`
Department string `json:"department"`
Designation string `json:"designation"`
}
type Employees struct {
Meta []Employee `json:"meta"`
}
When you try to unmarshal the provided string into a Employees var it will read the annotations and know where to place each field. You can find the working example at Golang Playground. I added a string representation to the Employee struct so that fmt.Println output is more redable.
In the case of having an extra nested key ({meta: {data: [...]}}), the types would be as follows:
type Employee struct {
ID int `json:"id"`
Name string `json:"name"`
Department string `json:"department"`
Designation string `json:"designation"`
}
type EmployeesData struct {
Data []Employee `json:"data"`
}
type Employees struct {
Meta EmployeesData `json:"meta"`
}
You can find the working example at Golang Playground too.
NOTE: I do not have context to name the structs properly, so I used Employees and EmployeesData but you should use more descriptive names that help understanding what the whole object represents and not only the meta and data fields.

Related

Why i get this error when trying to retrieve data from db golang gorm?

This is how i am trying to retrieve data
func getBoard(c *gin.Context) {
var board models.Board
database.DB.Where("id = ?", 1).Find(&board)
c.JSON(http.StatusOK, board)
}
and in postman i get all values right but todos is null
{
"id": 1,
"owner": 20,
"name": "name",
"generated_link": "",
"todos": null
}
in logs i see this error:
sql: Scan error on column index 4, name "todos": unsupported Scan, storing driver.Value type []uint8 into type *[]models.TodoStructure
this is model:
type Board struct {
Id uint `gorm:"primaryKey;autoIncrement;unique" json:"id"`
Owner uint `json:"owner"`
Name string `json:"name"`
GeneratedLink string `gorm:"default:''" json:"generated_link"`
Todos []TodoStructure `gorm:"type:jsonb;" json:"todos"`
}
type TodoStructure struct {
Id string `json:"id"`
Text string `json:"text"`
Completed bool `json:"completed"`
Important bool `json:"important"`
}
Please help how to get rid of this error and get todos rightly.
I tried to search in google but no result.
I am using gorm and postgresql as db

What struct can I use to decode a JSON array of arrays of strings?

I have the following JSON that I need do decode in Golang:
{
"name":"test",
"tags":[
[
"browser",
"Chrome 28.0.1500"
],
[
"browser.name",
"Chrome"
]
]
}
I came with some struct and some variations, but it still doesn't work:
type Response struct {
Name string `json:"name"`
Tags map[int][]string `json:"tags"`
}
https://play.golang.org/p/WuVEHDLCS6H
How can I achieve the desired result?
"tags" is an array of arrays holding string values. So simply use a [][]string in Go to model it:
type Response struct {
Name string `json:"name"`
Tags [][]string `json:"tags"`
}
After unmarshaling printing the response:
fmt.Printf("%+v", response)
Output is (try it on the Go Playground):
{Name:test Tags:[[browser Chrome 28.0.1500] [browser.name Chrome]]}

Json Response - Accessing objects in an array

I'm attempting to access an object in an Json response, but not sure how. How can I access ID 11 using rest-assured, where ObjID1 and ObjID2 are unique UUID's?
"ObjID1": [
{
"ID": "11",
"NAME": "XYZ",
"GENDER": "M"
}
]
"ObjID2": [
{
"ID": "12",
"NAME": "Z",
"GENDER": "F"
}
]
To assert element's value you can use
then().body("ObjID1.ID[0]", equalTo("11"))
Indexing ID field with [0] allows you to get the ID of first JSON Object in the Array.
If you want to get this value for further processing then you can extract it like this:
JsonPath path = JsonPath.from("json file or json String");
List<HashMap<String, Object>> listOfJsonObjects = path.get("ObjID1");
We parsed the JSON and by using the path.get method we save Array of JSON Objects inside List of HashMaps. Each element in the list is the JSON Object.
In order to access first JSON Object you can use
HashMap<String, Object> jsonObject = listOfJsonObjects.get(0);
and then, using classic HashMap methods you can get specific element in the JSON Object like this:
jsonObject.get("ID");
The above will return "11"
Note that you will have to make a cast to String to get the value. Values in the HashMap are objects because JSON Objects in the array may contain nested Arrays or Objects.
String firstId = (String) jsonObject.get("ID");

What is the meaning of []json.Rawmessage

What is the meaning of []json.Rawmessage. Its within this structure here:
type Request struct {
Jsonrpc string `json:"jsonrpc"`
Method string `json:"method"`
Params []json.RawMessage `json:"params"`
ID interface{} `json:"id"`
}
I know its a slice of type json. I do not understand what the .RawMessage is referring to. I tried looking it up in both golang tour and my golang book. Also ultimately I know Params is type []json.Rawmessage being bundled into another type called Request
Futhermore:
What is going on with these segments json:"jsonrpc". Is a string literal somehow being attached to var? Again this is not in golang tour or my golang book. Thanks for your time.
[] is defining a slice
json is the package import name (from your import statement above)
RawMessage is the type within the package. In this case for a []byte type.
json:"params" is a field tag. The json package reads it with reflection and determines what name to use for json.
Most of the time time you need to look in to the package doc rather than some book and the online tour.
The json:"jsonrpc" is a struct tag.
For this specific case the json.Marshal function will read that struct tag and return the JSON field name with the given value. For more about "encoding/json" struct tags usage: https://golang.org/pkg/encoding/json/#Marshal
For RawMessage, you can read more about it here https://golang.org/pkg/encoding/json/#RawMessage
type RawMessage []byte
Normally I use it when having a "generic" kind of JSON object that don't need to be process right the way (maybe I just send them to another service, or I will unmarshall it later depending on conditions). For example (I will use your Request struct):
jsonString := `[
{
"id": 123,
"method": "getSomething",
"params": [{"A": 1, "B": 2}]
}
{
"id": 123,
"method": "getSomethingElse",
"params": [{"C": 1, "D": 2}]
}
]`
With this processing code:
var requests []Request
json.Unmarshal([]byte(jsonString), &requests)
// if no error, you will have 2 items in requests
// requests[0].Params[0] is equal to []byte(`{"A": 1, "B": 2}`)
// requests[1].Params[0] is equal to []byte(`{"C": 1, "D": 2}`)
for _, req := range requests {
if req.Method == "getSomething" {
justProxyThisRequestToAnotherService(req)
} else if req.Method == "getSomethingElse" {
var params []map[string]int
json.Unmarshal(req.Params, &params)
// then do something with params
}
}

ELM how to decode different value in json array

I have a JSON array with different value in the array and I don't know how to parse it. Here is an example:
[
{
"firstname": "John",
"lastname": "Doe",
"age": 30
},
{
"companyName": "Doe enterprise",
"location": "NYC",
"numberOfEmployee": 10
}
]
So my JSON is like this, the first element of the array is an user, and the second a company.
I have the equivalent in Elm:
type alias User =
{ firsname : String
, lastname : String
, age : Int
}
type alias Company =
{ companyName : String
, location : String
, numberOfEmployee : Int
}
then: Task.perform FetchFail FetchPass (Http.get decodeData url).
So how do I get my User and Company pass in my FetchPass function ?
There is something like Json.Decode.at but it's for object only.
Here there a way to do something like this ?
decodeData =
Json.at [0] userDecoder
Json.at [1] companyDecoder
Json.at works for array indexes as well. First you'll need a Data type to hold the user and company:
import Json.Decode as Json exposing ((:=))
type alias Data =
{ user : User
, company : Company
}
And you'll need simple decoders for user and company:
userDecoder : Json.Decoder User
userDecoder =
Json.object3 User
("firstname" := Json.string)
("lastname" := Json.string)
("age" := Json.int)
companyDecoder : Json.Decoder Company
companyDecoder =
Json.object3 Company
("companyName" := Json.string)
("location" := Json.string)
("numberOfEmployee" := Json.int)
And finally you can use Json.at to get the values at those array indexes. The difference from your example is that you need to pass a string containing an integer index instead of an int:
dataDecoder : Json.Decoder Data
dataDecoder =
Json.object2 Data
(Json.at ["0"] userDecoder)
(Json.at ["1"] companyDecoder)

Resources