Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to create additional keys and arrays #128

Open
SimplySeth opened this issue Oct 21, 2022 · 1 comment
Open

How to create additional keys and arrays #128

SimplySeth opened this issue Oct 21, 2022 · 1 comment

Comments

@SimplySeth
Copy link

SimplySeth commented Oct 21, 2022

Okay so I have a structure like so ...
{"Controllers": [{"Controller": { "Key":"Value"...}}]
I would like to add a new key named "Ports" for an array so
{"Controllers": [{"Controller": { "Key":"Value"...}, "Ports":[]}]

I tried
jblob.S("Controllers").Index(i).S("Controller").Array("Ports")

The query works for jblob.S("Controllers").Index(i).S("Controller") BTW

which gives me ...

Cannot initialize one variable with 2 values

What the proper way to do it?

@mihaitodor
Copy link
Contributor

Hey @SimplySeth, try this:

package main

import (
	"github.com/Jeffail/gabs/v2"
)

func main() {
	obj, err := gabs.ParseJSON([]byte(`{"Controllers": [{"Controller": { "Key":"Value"}}]}`))
	if err != nil {
		panic(err)
	}

	controller := obj.Path(`Controllers.0.Controller`)
	_, err = controller.Array("Ports")
	if err != nil {
		panic(err)
	}
	err = controller.ArrayAppendP(1234, "Ports")
	if err != nil {
		panic(err)
	}
	objStr, err := obj.MarshalJSON()
	if err != nil {
		panic(err)
	}
	if string(objStr) != `{"Controllers":[{"Controller":{"Key":"Value","Ports":[1234]}}]}` {
		panic(string(objStr))
	}
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants