{"record":{"id":"a763049dbc052144","repo":"OpenNHP/opennhp","slug":"failed-to-unmarshal-json-s-to-struct-w","errorCode":null,"errorMessage":"failed to unmarshal JSON %s to struct: %w","messagePattern":"failed to unmarshal JSON (.+?) to struct: %w","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"nhp/utils/utils.go","lineNumber":146,"sourceCode":"\t}\n\n\treturn nil\n}\n\nfunc LoadJsonFileAsStruct(filePath string) (any, error) {\n\tif filePath == \"\" {\n\t\treturn nil, fmt.Errorf(\"file path cannot be empty\")\n\t}\n\n\tjsonData, err := os.ReadFile(filePath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read file: %w\", err)\n\t}\n\n\tvar data map[string]any\n\n\tif err := json.Unmarshal(jsonData, &data); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal JSON %s to struct: %w\", string(jsonData), err)\n\t}\n\n\treturn data, nil\n}\n\nfunc UpdateTomlConfig(filePath string, key string, value any) error {\n\tcontent, err := os.ReadFile(filePath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar newContent string\n\n\tswitch value := value.(type) {\n\tcase string:\n\t\tre := regexp.MustCompile(`(?m)^\\s*` + key + `\\s*=\\s*\".+\"\\s*$`)\n\t\tnewContent = re.ReplaceAllString(string(content), fmt.Sprintf(\"%s = \\\"%s\\\"\", key, value))\n\tdefault:","sourceCodeStart":128,"sourceCodeEnd":164,"githubUrl":"https://github.com/OpenNHP/opennhp/blob/6e04ca5ff03222a699c24205cd4bf8fee9af7ffe/nhp/utils/utils.go#L128-L164","documentation":"After successfully reading the file, LoadJsonFileAsStruct unmarshals it into map[string]any and wraps json.Unmarshal failures. It means the file content is not syntactically valid JSON (or, since it targets map[string]any, the top-level value is not a JSON object). The offending file content is embedded in the message for diagnosis.","triggerScenarios":"Calling LoadJsonFileAsStruct on a file containing TOML/YAML instead of JSON, an empty or truncated file, a JSON array or scalar at the top level (cannot unmarshal into map[string]any), or a partially written/corrupted file.","commonSituations":"An operator hand-edited the trust-anchor file and left a trailing comma or comments (invalid JSON); the file was saved by a different tool in TOML format; concurrent write truncated the file mid-update; encoding issues like BOM at the start of the file.","solutions":["Validate the file with `python3 -m json.tool <file>` or jq to see the exact syntax error and fix the content.","Ensure the top-level JSON value is an object ({...}); wrap arrays/scalars into an object or change the loader.","Regenerate the file programmatically with SaveStructAsJsonFile instead of hand-editing.","If files are updated in place, write atomically (temp file + rename) so readers never see partial content; strip a UTF-8 BOM if present."],"exampleFix":"// before\n// file content: 'key = \"value\"'  (TOML, invalid JSON)\ndata, err := utils.LoadJsonFileAsStruct(\"etc/ta.toml\")\n// after\n// file content: {\"key\": \"value\"}\ndata, err := utils.LoadJsonFileAsStruct(\"etc/ta.json\")","handlingStrategy":"validation","validationCode":"raw, err := os.ReadFile(path)\nif err == nil && json.Valid(raw) {\n    // safe to call LoadJsonFileAsStruct\n}","typeGuard":null,"tryCatchPattern":"data, err := utils.LoadJsonFileAsStruct(path)\nvar syn *json.SyntaxError\nif errors.As(err, &syn) {\n    return fmt.Errorf(\"invalid JSON at offset %d: %v\", syn.Offset, syn)\n}","preventionTips":["Generate these files only via SaveStructAsJsonFile; never hand-edit in place.","Write atomically (temp file + os.Rename) so readers never see partial content.","Run `jq empty file` in CI/provisioning to validate JSON artifacts.","Remember map[string]any requires a top-level JSON object; avoid arrays/scalars at the root."],"tags":["go","json","parsing","validation"],"backgroundTag":"json-unmarshal-failed","analyzedSha":"6e04ca5ff03222a699c24205cd4bf8fee9af7ffe","analyzedAt":"2026-09-07T15:44:59.941Z","contentChangedAt":"2026-09-07T15:44:59.941Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}