Skip to content

Instantly share code, notes, and snippets.

@ryupold
Last active May 7, 2018 17:05
Show Gist options
  • Save ryupold/0df48798c0299e7198d43a4ea4b52ac4 to your computer and use it in GitHub Desktop.
Save ryupold/0df48798c0299e7198d43a4ea4b52ac4 to your computer and use it in GitHub Desktop.
Convert *.resx file to JSON
package main
import (
"encoding/xml"
"fmt"
"io/ioutil"
"os"
"strings"
)
type data struct {
Name string `xml:"name,attr"`
Value string `xml:"value"`
}
type datas []data
type resx struct {
Data []data `xml:"data"`
}
func main() {
filePath := os.Args[1]
fmt.Printf("reading from %s\n", filePath)
data, err := ioutil.ReadFile(filePath)
try(err)
var root resx
try(xml.Unmarshal(data, &root))
jsonFile, err := os.OpenFile(toJSONEnding(filePath), os.O_CREATE|os.O_RDWR, 666)
try(err)
_, err = jsonFile.WriteString("{\n")
try(err)
indent := " "
for i, d := range root.Data {
if i != len(root.Data)-1 {
_, err = fmt.Fprintf(jsonFile, `%s"%s": "%s",%s`, indent, d.Name, escape(d.Value), "\n")
} else {
_, err = fmt.Fprintf(jsonFile, `%s"%s": "%s"`, indent, d.Name, escape(d.Value))
}
try(err)
}
_,err = jsonFile.WriteString("\n}")
try(err)
try(jsonFile.Close())
fmt.Printf("written %d entries to %s\n", len(root.Data), filePath)
}
func escape(s string) (result string) {
result = strings.Replace(s, "\"", "\\\"", -1)
result = strings.Replace(result, "\n", "\\n", -1)
return
}
func toJSONEnding(filePath string) string {
jsonPath := strings.Replace(filePath, ".xml", ".json", -1)
jsonPath = strings.Replace(jsonPath, ".resx", ".json", -1)
if !strings.Contains(jsonPath, ".json") {
jsonPath = fmt.Sprintf("%s.json", filePath)
}
return jsonPath
}
func try(err error) {
if err != nil {
panic(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment