10 examples of 'golang read json file' in Go

Every line of 'golang read json file' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Go code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
58func readJsonFile(path string) (jsonData []byte, err error) {
59 jsonData = nil
60 _, err = os.Stat(path)
61 if err != nil {
62 if len(path) == 0 {
63 //log.log.With Println("Need request json file")
64 } else {
65 fmt.Printf("Not Found %s \n", path)
66 }
67 return
68 }
69
70 jsonData, err = ioutil.ReadFile(path)
71 if err != nil {
72 fmt.Printf("dots_client_controller.readJsonFile -- File error: %v\n", err)
73 return
74 }
75 return
76}
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

97func parseJSON(path string) *Config {
98 // parseJSON Read file(json) convert to *Config
99 b, err := ioutil.ReadFile(path)
100 if err != nil {
101 log.Fatalf("Failed to read config file: %s", err)
102 os.Exit(1)
103 }
104
105 j := new(Config)
106 err = json.Unmarshal(b, j)
107 if err != nil {
108 log.Fatalf("Failed to parse config file: %s", err)
109 os.Exit(1)
110 }
111
112 return j
113}
367func getJSON(filepath string, v interface{}) error {
368 contents, err := ioutil.ReadFile(filepath)
369 if err != nil {
370 return fmt.Errorf("Could not open file '%s': %s", filepath, err)
371 }
372
373 // Decode the JSON into the provided interface
374 err = json.Unmarshal(contents, v)
375 if err != nil {
376 return fmt.Errorf("Could not unmarshal JSON: %s", err)
377 }
378
379 return nil
380}
340func ReadJsonFileWithLocalConfig(filePath string) []byte {
341 // get message printer
342 msgPrinter := i18n.GetMessagePrinter()
343
344 inputFile, err := filepath.Abs(filePath)
345 if err != nil {
346 cliutils.Fatal(cliutils.CLI_GENERAL_ERROR, "%v", err)
347 }
348 localConfigFile := filepath.Join(filepath.Dir(inputFile), "hzn.json")
349 localConfigFile = filepath.Clean(localConfigFile)
350
351 // no local configuration file
352 if _, err := os.Stat(localConfigFile); err == nil {
353 return cliutils.ReadJsonFile(filePath)
354 }
355
356 // check if the local configuration file has been used already
357 useLocalConfig := true
358 if localConfigFile == PROJECT_CONFIG_FILE || localConfigFile == PACKAGE_CONFIG_FILE || localConfigFile == USER_CONFIG_FILE {
359 useLocalConfig = false
360 cliutils.Verbose(msgPrinter.Sprintf("Local configuration %v has been setup at the beginning of this command. Will not setup twice.", localConfigFile))
361 }
362
363 orig_env_vars := map[string]string{}
364 hzn_vars := map[string]string{}
365 metadata_vars := map[string]string{}
366 if useLocalConfig {
367 orig_env_vars = GetEnvVars()
368 hzn_vars, metadata_vars, err = SetEnvVarsFromConfigFile(localConfigFile, orig_env_vars, false)
369 if err != nil {
370 cliutils.Fatal(cliutils.CLI_GENERAL_ERROR, msgPrinter.Sprintf("Failed to set the environment variable from the local configuration file %v for file %v. Error: %v", localConfigFile, filePath, err))
371 }
372 }
373
374 contents := cliutils.ReadJsonFile(filePath)
375
376 if useLocalConfig {
377 // restore the env vars
378 err = RestoreEnvVars(orig_env_vars, hzn_vars, metadata_vars)
379 if err != nil {
380 cliutils.Fatal(cliutils.CLI_GENERAL_ERROR, msgPrinter.Sprintf("Failed to restore the environment variable after using local configuration file %v. %v", useLocalConfig, err))
381 }
382 }
383
384 return contents
385}
136func readJSONFile(filename string) (interface{}, error) {
137 f, err := os.Open(filename)
138 if err != nil {
139 return nil, err
140 }
141 defer f.Close()
142
143 return readJSON(f)
144}
126func (l *jsonReferenceLoader) LoadJSON() (interface{}, error) {
127
128 var err error
129
130 reference, err := gojsonreference.NewJsonReference(l.JsonSource().(string))
131 if err != nil {
132 return nil, err
133 }
134
135 refToUrl := reference
136 refToUrl.GetUrl().Fragment = ""
137
138 var document interface{}
139
140 if reference.HasFileScheme {
141
142 filename := strings.Replace(refToUrl.GetUrl().Path, "file://", "", -1)
143 if runtime.GOOS == "windows" {
144 // on Windows, a file URL may have an extra leading slash, use slashes
145 // instead of backslashes, and have spaces escaped
146 if strings.HasPrefix(filename, "/") {
147 filename = filename[1:]
148 }
149 filename = filepath.FromSlash(filename)
150 }
151
152 document, err = l.loadFromFile(filename)
153 if err != nil {
154 return nil, err
155 }
156
157 } else {
158
159 document, err = l.loadFromHTTP(refToUrl.String())
160 if err != nil {
161 return nil, err
162 }
163
164 }
165
166 return document, nil
167
168}
8func main() {
9 t, err := test_json_loader.Load_json("../common_input_test.json")
10 if err != nil {
11 fmt.Println(err.Error())
12 } else {
13 for _, e := range t {
14 fmt.Printf("%v\n", e.ToString())
15 }
16 }
17
18}
128func parseJSON(file string) []endpointDetails {
129 jsonFile, err := os.Open(file)
130 if err != nil {
131 log.Fatal(err)
132 }
133 defer jsonFile.Close()
134
135 byteValue, err := ioutil.ReadAll(jsonFile)
136 if err != nil {
137 panic(err)
138 }
139 var temp []endpointDetails
140 err = json.Unmarshal(byteValue, &temp)
141 if err != nil {
142 panic(err)
143 }
144 return temp
145}
11func main() {
12 if len(os.Args) != 2 {
13 log.Fatalf("The usage of the command is: \n\t%s <log-file.json>", os.Args[0])
14 }
15
16 file, err := os.Open(os.Args[1])
17 if err != nil {
18 log.Fatal(err)
19 }
20
21 closeFile := func(file *os.File) {
22 if err := file.Close(); err != nil {
23 log.Fatal(err)
24 }
25 }
26 defer closeFile(file)
27
28 scanner := bufio.NewScanner(file)
29 for scanner.Scan() {
30 line := scanner.Text()
31
32 var entry interface{}
33 if err := json.Unmarshal([]byte(line), &entry); err != nil {
34 log.Printf("failed to unmarshal a log entry: %s\n", line)
35 }
36
37 m := entry.(map[string]interface{})
38 if payload, ok := m["textPayload"]; ok {
39 // use fmt.Printf here instead of log.Printf to avoid the time and code location info the log package provides
40 fmt.Printf("%s", payload)
41 } else {
42 log.Printf("the log entry does not have the `textPayload` field: %s\n", line)
43 }
44 }
45
46 if err := scanner.Err(); err != nil {
47 log.Fatal(err)
48 }
49}
11func main() {
12 testFile, err := os.Open("test.json")
13 if err != nil {
14 log.Fatal("Error opening filter file:", err)
15 }
16 defer testFile.Close()
17
18 jsonDecoder := json.NewDecoder(testFile)
19 var data interface{}
20 err = jsonDecoder.Decode(&data)
21 if err != nil {
22 log.Fatal("Error decoding filters:", err)
23 }
24
25 t := jsongen.Parse("Test", data)
26
27 fmt.Println(t.Format())
28}

Related snippets