Convert a string for access to a json key

Hello

I have a map (string) of “tag” to convert “words” into a text
this list of “Tags” must be replaced by values coming from a structure

sample:
var users struc {
login String json:" options "
passwd String json:" options "
}
var folders struc {
arch String json:" folders "
dest String json:" folders "
}

var TAGS = map [string] string {
"{login}": "users.login",
"{passwd}": "users.passwd",
"{archive}": "folders.arch",
"{dest}": "folders.dest",
}

Something like this:

var test = "Name = {login} archive = {archive} destination = {dest} / {login}"
var realTest = ReplaceTag (test, &TAGS)

I don’t know how to convert the strings from the value to the real value of the structure.
I know how to do it directly but not when it is in the form of a string

i make a “Go Playground” to be more clear: https://play.golang.org/p/qhmYnwiB5NO

thank you in advance

So your question is how to implement ReplaceTag to convert

"Name = {login} archive = {archive} destination = {dest} / {login}"

to

"Name = users.login archive = folders.arch destination = folders.dest / users.login"

?

Did I get this correctly? What are folders and users used for?

Not exactly
Want to replace with the “values” of the structure, The struct itself reflecting the result a JSON file

i make a “Go Playground” to be more clear: Go Playground - The Go Programming Language

Note: This work if i use le “TAG” map in the main() like this:

TAGS := map[string]string{
        "{login}":   conf.Users.Login,
        "{passwd}":  conf.Users.Passwd,
        "{archive}": conf.Folders.Archive,
        "{dest}":    conf.Folders.Destination,
    }

But i need this Map elsewhere, so i must declared it in global

in PHP we can do something like this:

$Bar = “a”;
$Foo = “Bar”;
$World = “Foo”;
$Hello = “World”;
$a = “Hello”;

$a; //Returns Hello
$$a; //Returns World
$$$a; //Returns Foo
$$$$a; //Returns Bar
$$$$$a; //Returns a

Thanks

That’s very “eval-like.” Go doesn’t have anything like an eval function. You could do something with functions like this: https://play.golang.org/p/mFsFrVAQjG_I or you could could use templates: https://play.golang.org/p/bjHovjaoR7W

1 Like

Great ! thank you so much

I changed things slightly but the principle is there, it works

var TAGS = map[string]string{
    "{login}":   "Users.Login",
    "{passwd}":  "Users.Passwd",
    "{archive}": "Folders.Archive",
    "{dest}":    "Folders.Destination",
}

func main() {
    conf := config{}
    json.Unmarshal(jsonData, &conf)

    var buf bytes.Buffer
    for tag, value := range TAGS {
        template.Must(template.New("").Parse("{{."+value+"}}")).Execute(&buf, conf)
        TestString = strings.ReplaceAll(TestString, tag, string(buf.Bytes()))
        buf.Reset()
    }
    fmt.Println(TestString)
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.