go-i18n icon indicating copy to clipboard operation
go-i18n copied to clipboard

Any example present how to use message format in JSON

Open KingWu opened this issue 4 years ago • 1 comments

Hi, i feel confuse on how to use message format in Json. Any demo example?

KingWu avatar Dec 08 '20 06:12 KingWu

key point:

bundle.RegisterUnmarshalFunc("json", json.Unmarshal)

example code

https://github.com/CarsonSlovoka/go-i18n/blob/d81b3367d02fa33d2d37f37ea05050b335098107/v2/example/basic.go#L220-L235

👆 where simpleTest

Other: custom format

default is support TOML, YAML, JSON

If the above format is not satisfied for you, you can define your Unmarshal Function

// UnmarshalFunc unmarshals data into v.
type UnmarshalFunc func(data []byte, v interface{}) error

normally v should be something like this:

map[string]interface{}

I mean, suppose your contents is below

[IDHi]
other="Hi"

https://github.com/nicksnyder/go-i18n/blob/0c6ce6ac1e8c119993c3d5638af4f7cd67ff068a/v2/i18n/parse.go#L42

  • buf: file contents ([]byte)
  • raw: you must let your unmarshalFunc create an item like that {interface{} | map[string]interface{}{"IDHi": Hi}

CarsonSlovoka avatar May 27 '21 11:05 CarsonSlovoka

There is a TOML example here and you can just convert that file to an equivalent JSON file using a converter like https://pseitz.github.io/toml-to-json-online-converter/ to get the equivalent JSON file:

{
  "HelloPerson": "Hello {{.Name}}",
  "MyUnreadEmails": {
    "description": "The number of unread emails I have",
    "one": "I have {{.PluralCount}} unread email.",
    "other": "I have {{.PluralCount}} unread emails."
  },
  "PersonUnreadEmails": {
    "description": "The number of unread emails a person has",
    "one": "{{.Name}} has {{.UnreadEmailCount}} unread email.",
    "other": "{{.Name}} has {{.UnreadEmailCount}} unread emails."
  }
}

There are also a JSON example in this test: https://github.com/nicksnyder/go-i18n/blob/7c6508d75732c7b2b41bc9f46ce9e9a3c7fefff4/i18n/bundle_test.go#L101-L118

nicksnyder avatar Feb 03 '24 04:02 nicksnyder