Get value JSON to create a nested in golang - json

I'm trying to create dynamically nested json from value FIELD_QUESTION and FIELD_ANSWER in golang.
my result json
{
"jumlahdata": 2,
"result": [
{
"QUICK_DATA_H_ID": "1",
"ORDER_TRX_H_ID": "1",
"FIELD_QUESTION": "FULLNAME",
"FIELD_ANSWER": "RUBEN",
"DTM_CRT": "2019-08-28T16:25:15.757Z"
},
{
"QUICK_DATA_H_ID": "2",
"ORDER_TRX_H_ID": "1",
"FIELD_QUESTION": "ALAMAT_KTP",
"FIELD_ANSWER": "jalandisana",
"DTM_CRT": "2019-08-28T16:25:15.757Z"
}
],
"statusdb": 200,
"statusload": 200,
"statusquery": 200
}
expected result nested
{
"jumlahdata": 1,
"result": [
{
"QUICK_DATA_H_ID": "1",
"ORDER_TRX_H_ID": "1",
"QUESTION":[{
"FULLNAME": "RUBEN",
"ALAMAT_KTP": "jalandisana",
}]
"DTM_CRT": "2019-08-28T16:25:15.757Z"
}
],
"statusdb": 200,
"statusload": 200,
"statusquery": 200
}
can anyone help with this? Please let me know if I haven't been clear enough!

maybe this tool can help you JSON-to-Go - https://mholt.github.io/json-to-go/
type AutoGenerated struct {
Jumlahdata int `json:"jumlahdata"`
Result []struct {
QUICKDATAHID string `json:"QUICK_DATA_H_ID"`
ORDERTRXHID string `json:"ORDER_TRX_H_ID"`
QUESTION []struct {
FULLNAME string `json:"FULLNAME"`
ALAMATKTP string `json:"ALAMAT_KTP"`
} `json:"QUESTION"`
DTMCRT time.Time `json:"DTM_CRT"`
} `json:"result"`
Statusdb int `json:"statusdb"`
Statusload int `json:"statusload"`
Statusquery int `json:"statusquery"`
}

For that, personally i love to use gabs module which allows to handle those kind of situation in a more human friendly way.
For installing the module use:
go get github.com/Jeffail/gabs/v2
So take your json string and pass it to gabs.ParseJSON as follows
// jsonParsed var contains a set of functions to play arround
jsonParsed, _ := gabs.ParseJSON([]byte(`{
"outter":{
"inner":{
"value1":10,
"value2":22
},
"alsoInner":{
"value1":20,
"array1":[
30, 40
]
}
}
}`))
// you can check for keys existence
exists := jsonParsed.Exists("outter", "inner", "value1")
// exists == true
// you can pretty print your json
fmt.Println(jsonObj.StringIndent("", " "))
// you can search for specific values in your inner object
value, ok = jsonParsed.Search("outter", "inner", "value1").Data().(float64)
// value == 10.0, ok == true
// and much more ...
Take a look at the documentation

Related

Enumerate slice entries

If I have this output
Stuff {
"Items": [
{
"title": "test1",
"id": "1",
},
{
"title": "test",
"id": "2",
},
],
"total": 19
},
}
But want this instead:
stuff {
"Items": [
1:{
"title": "test1",
"id": "1",
},
2:{
"title": "test",
"id": "2",
},
],
"total": 19
},
}
Currently, my structs are build like this:
Stuff struct {
Items []Items `json:"items"`
Total int `json:"total"`
} `json:"stuff"`
type Items struct {
Title string `json:"title"`
ID string `json:"id"`
}
I initiate a slice by:
stuff := make([]Items, 10) // Lets say I have 10 entries
And append by:
Stuff.Items = stuff
Stuff.Total = len(Stuff.Items)
Now I am unsure on how to numerate that. So for every item entries, there should be a number, starting from 1 - 10 (In this example)
Given your Stuff and Items type declarations, here's a simple data structure and its JSON dump:
s := Stuff{Items: []Items{Items{"test1", "1"}, Items{"test2", "2"}}, Total: 10}
j, err := json.MarshalIndent(s, "", " ")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(j))
JSON:
{
"items": [
{
"title": "test1",
"id": "1"
},
{
"title": "test2",
"id": "2"
}
],
"total": 10
}
To see what you want instead, there's no magic json package call to do that. You'll have to create a new data structure that reflects the structure of your desired output.
In this case a simple map will do:
m := make(map[string]Items)
for _, item := range s.Items {
m[item.ID] = item
}
And now if you JSON-dump this map, you get:
{
"1": {
"title": "test1",
"id": "1"
},
"2": {
"title": "test2",
"id": "2"
}
}
Note that I'm not wrapping it with Stuff now, because Stuff has different fields. Go is statically typed, and each struct can only contain the fields you declared it to have.

One of the elements of the array as an object

The question is how to get the "from" element? The rest is not a problem
I know that in https://github.com/json-iterator/ it can be done, but I could not figure out how it works there
Json:
{
"ab": 123456789,
"cd": [
[
4,
1234,
123456,
1000000001,
1234567890,
"text",
{
"from": "123456"
}
],
[
4,
4321,
654321,
1000000001,
9876543210,
"text",
{
"from": "654321"
}
]
]
}
Golang:
type test struct {
Ab int `json:"ab"`
Cd [][]interface{} `json:"cd"`
}
var testvar test
json.Unmarshal(Data, &testvar)
testvar.Cd[0][6]["from"].(string)
Error:
invalid operation: testvar.Cd[0][6]["from"] (type interface {} does not support indexing)
It's simple: it is a map[string]interface{} hence
m, ok := testvar.Cd[0][6].(map[string]interface{})
fmt.Println(m, ok, m["from"])
https://play.golang.org/p/XJGs_HsxMfZ

JSON transformation in node.js

I want to transform my data from one json structure to another. What is the best way to do it?
Here is my original resource (customer) structure is:
{
"id": "123",
"data": {
"name": "john doe",
"status": "active",
"contacts": [
{
"email": "john#email.com"
},
{
"phone": "12233333"
}
]
}
}
I want to change it to:
{
"id": "123",
"name": "john doe",
"status": "active",
"contacts": [
{
"email": "john#email.com"
},
{
"phone": "12233333"
}
]
}
Keeping in mind that I might have an array of resources(customers) being returned in GET /customers cases. I want to change that to an array of new data type.
If customer object is array of object then below will help you to get desire format result
var result = customerObj.map(x => {
return {
id: x.id,
name: x.data.name,
status: x.data.status,
contacts: x.data.contacts
};
});
here I have used Object.assign() it will be helpful to you
var arr={
"id": "123",
"data": {
"name": "john doe",
"status": "active",
"contacts": [
{
"email": "john#email.com"
},
{
"phone": "12233333"
}
]
}
}
arr=Object.assign(arr,arr.data);
delete arr['data'];
console.log(arr);
You have to Json.parse the json into variable, and then loop through the array of objects, changes the object to the new format, and then JSON.stringify the array back to json.
Example code
function formatter(oldFormat) {
Object.assign(oldFormat, oldFormat.data);
delete oldFormat.data;
}
let parsedData = JSON.parse(Oldjson);
//Take care for array of results or single result
if (parsedData instanceof Array) {
parsedData.map(customer => formtter(customer));
} else {
formatter(parsedData);
}
let newJson = JSON.stringify(parsedData);
console.log(newJson);
Edit
I made the formatter function cleaner by using Kalaiselvan A code

Put Data in mutlple branch of Array : Json Transformer ,Scala Play

i want to add values to all the arrays in json object.
For eg:
value array [4,2.5,2.5,1.5]
json =
{
"items": [
{
"id": 1,
"name": "one",
"price": {}
},
{
"id": 2,
"name": "two"
},
{
"id": 3,
"name": "three",
"price": {}
},
{
"id": 4,
"name": "four",
"price": {
"value": 1.5
}
}
]
}
i want to transform the above json in
{
"items": [
{
"id": 1,
"name": "one",
"price": {
"value": 4
}
},
{
"id": 2,
"name": "two",
"price": {
"value": 2.5
}
},
{
"id": 3,
"name": "three",
"price": {
"value": 2.5
}
},
{
"id": 4,
"name": "four",
"price": {
"value": 1.5
}
}
]
}
Any suggestions on how do i achieve this. My goal is to put values inside the specific fields of json array. I am using play json library throughout my application. What other options do i have instead of using json transformers.
You may use simple transformation like
val prices = List[Double](4,2.5,2.5,1.5).map(price => Json.obj("price" -> Json.obj("value" -> price)))
val t = (__ \ "items").json.update(
of[List[JsObject]]
.map(_.zip(prices).map(o => _._1 ++ _._2))
.map(JsArray)
)
res5: play.api.libs.json.JsResult[play.api.libs.json.JsObject] = JsSuccess({"items":[{"id":1,"name":"one","price":{"value":4}},{"id":2,"name":"two","price":{"value":2.5}},{"id":3,"name":"three","price":{"value":2.5}},{"id":4,"name":"four","price":{"value":1.5}}]},/items)
I suggest using classes, but not sure this fits to your project because it's hard to guess how your whole codes look like.
I put new Item manually for simplicity. You can create items using Json library :)
class Price(val value:Double) {
override def toString = s"{value:${value}}"
}
class Item(val id: Int, val name: String, val price: Price) {
def this(id: Int, name: String) {
this(id, name, null)
}
override def toString = s"{id:${id}, name:${name}, price:${price}}"
}
val price = Array(4, 2.5, 2.5, 1.5)
/** You might convert Json data to List[Item] using Json library instead. */
val items: List[Item] = List(
new Item(1, "one"),
new Item(2, "two"),
new Item(3, "three"),
new Item(4, "four", new Price(1.5))
)
val valueMappedItems = items.zipWithIndex.map{case (item, index) =>
if (item.price == null) {
new Item(item.id, item.name, new Price(price(index)))
} else {
item
}
}

json object accessing

i know its very simple thing but i m stucked on it
i have json variable with data as follow
var jsonText =
'[ { "user": [ { "Gender": "M", "Minage": "19", "Maxage": "30", "MaritalStatusId":"0", }]
},
{ "user":[ { "maritialtype": "Does not matter" }]
},
{ "user": [ { "Value": "No" }]
} ]';
var jsonObject = JSON.parse(jsonText);
now i can access gender as jsonObject[0].user[0].Gender
but i'm not able to access maritialtype and Value
For maritialtype:
jsonObject[1].user[0].maritialtype
For Value:
jsonObject[2].user[0].Value
Because you have an array of three objects, user, which is an array or one object. It's kind of a weird structure.