'Equivalent of PHP json_decode in Golang
Equivalent of PHP json_decode in Golang
Thanks to the following references :
PHP Manual : json_decode — Decodes a JSON string
php2golang : GoLang alternatives for PHP functions
To convert JSON data (strings or bytes) into Go types like structs, arrays, and slices, as well as unstructured data like maps and empty interfaces.
..
If you don’t know the structure of your JSON properties beforehand, you cannot use structs to unmarshal your data ..
Looking for an equivalent of PHP json_decode in Golang I go immediately to : Decoding JSON to Maps - Unstructured Data
With the code below :
package main
import (
"fmt"
"os"
"encoding/json"
)
func main() {
json := `{"key_0":{"key_1":"value_1","key_2":"value_2"},"key_3":"value_3"}`
json_decoded, err := Json_decode(json)
fmt.Println(json_decoded)
fmt.Println(json_decoded["key_0"])
return
}
func Json_decode(data string) (map[string]interface{}, error) {
var dat map[string]interface{}
err := json.Unmarshal([]byte(data), &dat)
return dat, err
}
We got this output :
map[key_0:map[key_1:value_1 key_2:value_2] key_3:value_3]
map[key_1:value_1 key_2:value_2]
If we add this line :
fmt.Println(json_decoded["key_0"]["key_1"])
We got this error :
invalid operation: json_decoded["key_0"]["key_1"] (type interface {} does not support indexing)
To get value_1 we have to add these lines :
key_0 := json_decoded["key_0"].(map[string]interface{})
fmt.Println(key_0["key_1"])
But we don’t know the structure of the JSON
Lets say the JSON is a PHP array encoded with json_encode
The key can either be an int or a string and the value can be of any type.
So we may have to add these lines :
key_0 := json_decoded["key_0"].([]interface{})
fmt.Println(key_0[O])
Looking for an equivalent of PHP json_decode in Golang what do you suggest ?
Solution 1:[1]
encoding/json requires you to know your data structures,
you can use map[string]interface{} but it will be very slow and hard to manage.
package main
import (
//"encoding/json"
"jsonparser"
)
Alternative JSON parser for Go (10x times faster standard library)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | userM7Lh5621CD0P |
