To create map of array of map in golang - arrays

I want to create a json in golang for which I need to first create map of the following:
{"inputs": [{"data": {"image": {"url": "SOME_URL"}}}]}
how to create this map on golang. (for now even hardcoded will also work for me)

In a struct:
type SomeData struct {
Inputs []struct {
Data struct {
Image struct {
URL string `json:"url"`
} `json:"image"`
} `json:"data"`
} `json:"inputs"`
}
But if we wanted to be able to add things individually, AND be more idiomatic, we would do it like this:
type Image struct {
URL string `json:"url"`
}
type Data struct {
Image Image `json:"image"`
}
type Input struct {
Data Data `json:"data"`
}
type SomeData struct {
Inputs []Input `json:"inputs"`
}
Then, of course, we could always just use a map:
someData := map[interface{}]interface{}{}
It really just depends on which route you'd like to go. I suggest the second one as it gives you better fine-grained tooling without any pesky dirty tricks or code-clutter.
Hope this helps!

neededMap := make(map[string][]map[string]map[string]map[string]string)

Related

How to marshal an empty struct as an empty array

I'm not sure if the title accurately explains what I'm looking to do so I'll try to give as many details as I can.
I have a struct with nested structs that I am marshalling and sending out to an API. There are some requests that require my lowest level struct to be empty and I need its parent parameter to equal an empty array instead of null. If I use omitempty on the parameter, it will completely remove it from my request and the request will fail. If I use omitempty on the parameter's parameters, it causes the value to be null and the request will fail.
Here are the structs I am using for the request:
// SubscribeRequest is the top level wrapper for ICWS request bodies
SubscribeRequest struct {
ClientStateIsFresh bool `json:"clientStateIsFresh"`
StatisticKeys []StatisticKey `json:"statisticKeys"`
}
// StatisticKey is a value we want to pull from ICWS reporting
StatisticKey struct {
StatisticIdentifier string `json:"statisticIdentifier"`
ParameterValueItems []Parameter `json:"parameterValueItems"`
}
// Parameter is a filter applied when pulling statistics
Parameter struct {
ParameterTypeID string `json:"parameterTypeId"`
Value string `json:"value"`
}
And I need the marshalled JSON to look like this:
{
"clientStateIsFresh":true,
"statisticKeys":
[
{
"statisticIdentifier":"inin.system.interaction:ActiveCalls",
"parameterValueItems":
[
]
}
]
}
If I have anything other than this, the request fails. I don't get any errors, but it doesn't return any usable data. Any suggestions on how to accomplish this?
*Note: I did try using []*Parameter instead of []Parameter, but it gave me the same result.
If you want an empty array, you have to provide an empty slice.
StatisticKey{
StatisticIdentifier: "id.string",
ParameterValueItems: []Parameter{},
}

How can we initialize an array of type struct (which stores the json output) within a struct in golang

I need to initialize the following data structure which will store a json. The Attack_plans will hold multiple plans and if I loop through the GeneratePlan struct, I need all the plans that were stored.
type GeneratePlan struct {
Mode string `json:"mode"`
Name string `json:"name"`
Schema string `json:"schema"`
Version string `json:"version"`
Attack_plans []struct {
Attack_plan *Attack_plan `json:"attack-plan"`
} `json:"attack-plans"`
}
type Attack_plan struct {
Attack_resources []struct {
Attack_resource *Attack_resource `json:"attack-resource"`
} `json:"attack-resources"`
}
Can anyone please suggest something? If the data structure needs to be simplified before initializing it, then please suggest that as well. I am very new to golang so please ignore the best practices to follow. Any help is appreciated. Thanks!
why don't u just json.marshal your object to a json string, you can got answer
generatePlan := GeneratePlan{
Mode: "mode",
Name: "name",
Schema: "sachema",
Version: "version",
Attack_plans: []struct {
Attack_plan *Attack_plan `json:"attack-plan"`
}{
{Attack_plan: &Attack_plan{[]struct {
Attack_resource *Attack_resource `json:"attack-resource"`
}{
{Attack_resource: new(Attack_resource)},
{Attack_resource: new(Attack_resource)},
}}},
{Attack_plan: &Attack_plan{[]struct {
Attack_resource *Attack_resource `json:"attack-resource"`
}{
{Attack_resource: new(Attack_resource)},
{Attack_resource: new(Attack_resource)},
}}},
},
}
I found the solution! This simplifies the above data structure!
type GeneratePlan struct{
Mode string `json:"mode"`
Name string `json:"name"`
Schema string `json:"schema"`
Version string `json:"version"`
Attack_plans []struct1 `json:"attack-plans"`
}
type struct1 struct {
Attack_plan Attack_plan `json:"attack-plan"`
}
type Attack_plan struct{
Attack_resouces []struct2 `json:"attack-resources"`
}
type struct2 struct {
Attack_resource Attack_resource `json:"attack-resource"`
}

where to put code that operates on an array of structs?

If I have a struct and some code that processes arrays of this struct, where would be the place to put this code?
struct Thing {
var id : String
let type : ThingType
}
things:[Thing]?
I have code to retrieve values from a server which returns an array of 100 Thing. Where should the code go?
I've currently defined it as a static function of the Struct but would like to follow a convention, if there is one.
A function that retrieves Thing instances from a server most certainly should not be a member of Thing.
It's best to make a new protocol that declares the function, like so:
protocol ThingProvider {
func fetchThings() -> [Thing]
}
and a conforming type:
class DataBaseThingProvider: ThingProvider {
init() {
// open database connection
}
deinit() {
// close database connection
}
func fetchThings() -> [Thing] {
// fetch Things from database
}
}
This way, you can change the provider you use (Firebase, Parse, SQLite, CoreData, JSON, CSV, whatever.) by just swapping out the concrete provider class you use, and all other code can stay the same.
It also makes your code much more testable, because you can easily construct a mock provider, which decouples your tests from your production backend.
class MockThingProvider: ThingProvider {
func fetchThings() -> [Thing] {
return [
Thing(id: "MockThing1", type: thingType1),
Thing(id: "MockThing2", type: thingType2),
Thing(id: "MockThing3", type: thingType3)
]
}
}

Parse add string to array swift

My question is this with an example from the parse docs:
You have in parse the column with all kind of types, like string, array, etc.
Now I have the following kind of code:
var gameScore = PFObject(className:"GameScore")
gameScore["score"] = 1337
gameScore["playerName"] = "Sean Plott"
gameScore.saveInBackgroundWithBlock {
(success: Bool, error: NSError?) -> Void in
if (success) {
// The object has been saved.
} else {
// There was a problem, check error.description
}
}
Ok now I want to save another score behind the first score: 1337.
So when I retrieve from parse it will look like this: Sean: 1337, 1207.
Or something like that when I retrieve the name and scores. I have in parse it already set to be an array.
So my question is: How do I add a string to an array in parse.
Thank you beforehand.
You need "score" to be an Array in your DB. Then in your code, you do this:
gameScore.addObject([1337], forKey:"score")

Creating advanced structure with neast and arrays in golang

Hi guys I am trying to learn golang I am creating my own project which requires to create structure that I have hard times to write and initalized. I would be greatful if anyone can help me out with it.
{
"name":"message",
"args":[
{
"method":"joinChannel",
"params":{
"channel":"CHANNEL",
"name":"USERNAME",
"token":"XXXX",
"isAdmin":false
}
}
]
}
I was looking for some examples on google but only thing I could find was easie ones. This is what I came up
type Channel struct {
Name string `json:"name"`
Args []struct {
Method string `json:"method"`
Params struct {
Channel string `json:"channel"`
Name string `json:"name"`
Token string `json:"token"`
Isadmin bool `json:"isAdmin"`
} `json:"params"`
} `json:"args"`
}
Is there more transparent way to do it?
If you wanted to break the types out rather than having those anonymous declarations inline it would look like this;
type Channel struct {
Name string `json:"name"`
Args []Arg `json:"args"`
}
type Arg struct {
Method string `json:"method"`
Params Params `json:"params"`
}
type Params struct {
Channel string `json:"channel"`
Name string `json:"name"`
Token string `json:"token"`
Isadmin bool `json:"isAdmin"`
}
myChan := Channel{"Name", []Arg{ Arg{"Method", Params{ "Channel", "Name", "Token", true } } } }
You can separate nested struct like this.
http://play.golang.org/p/ghcMuFOdQC

Resources