Commit 42a46d2c authored by Boris Mühmer's avatar Boris Mühmer
Browse files

added functionality to pretty print JSON to a file

parent 821e8793
Loading
Loading
Loading
Loading
+33 −6
Original line number Diff line number Diff line
@@ -16,7 +16,7 @@ import (
func savegame2xml(filename string) (*data.Database, error) {
	f, err := os.Open(filename)
	if err != nil {
		return nil, fmt.Errorf("failed to open file", filename)
		return nil, fmt.Errorf("failed to open file %s", filename)
	}
	defer f.Close()

@@ -65,22 +65,24 @@ func Decode(filename string) (savegame *data.SaveGame, e error) {
				jdec := json.NewDecoder(strings.NewReader(r.DataJSON))
				jerr := jdec.Decode(&cn)
				if jerr != nil {
					fmt.Errorf("failed to decode JSON CharacterName: %v", jerr)
					return nil, fmt.Errorf("failed to decode JSON CharacterName: %v", jerr)
				}
				fmt.Printf("  => Firstname %s - Lastname %s\n", cn.Fn, cn.Ln)
			default:
				var v interface{}
				jerr := json.Unmarshal([]byte(r.DataJSON), &v)
				if jerr != nil {
					fmt.Errorf("failed to decode generic JSON: %v", jerr)
					return nil, fmt.Errorf("failed to decode generic JSON: %v", jerr)
				}
			}
		}
	}

	return
	return nil, nil
}

// DumpJSONContents extracts the JSON data from a savegame file and dumps them
// indented to a file.
func DumpJSONContents(filepath string, destdir string) error {
	_, filename := path.Split(filepath)

@@ -91,10 +93,35 @@ func DumpJSONContents(filepath string, destdir string) error {

	fmt.Printf("file: %s\n", filename)
	for i, c := range database.Collections.Collection {
		fmt.Printf(" - collection %s (%d)\n", c.Name, i)
		//fmt.Printf(" - collection %s (%03d)\n", c.Name, i)
		for j, r := range c.Records.Record {
			fmt.Printf("   - record %s (%d)\n", r.ID, j)
			//fmt.Printf("   - record %s (%04d)\n", r.ID, j)
			// beautify JSON and dump to file
			var msg string
			var result map[string]interface{}
			json.Unmarshal([]byte(r.DataJSON), &result)
			jtext, jmerr := json.MarshalIndent(result, "", "    ")
			//_, jmerr := json.MarshalIndent(result, "", "    ")
			if jmerr != nil {
				msg = fmt.Sprintf("error: %v", jmerr)
			} else {
				msg = "ok"
			}
			fmt.Printf("     JSON convert: %s\n", msg)
			//fmt.Printf("\n\n%s\n\n", string(jtext))

			if jmerr == nil {
				// dump to file
				outdirname := fmt.Sprintf("%s-%s", filename[:len(filename)-5], database.Build)
				outfilename := fmt.Sprintf("%03d-%s-%04d", i, c.Name, j)
				fmt.Printf(" - %s/%s\n", outdirname, outfilename)
				os.MkdirAll(path.Join(destdir, outdirname), os.ModeDir|0755)
				f, err := os.OpenFile(path.Join(destdir, outdirname, outfilename), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
				defer f.Close()
				if err == nil {
					f.WriteString(string(jtext))
				}
			}
		}
	}