JSON: Difference between revisions

Content added Content deleted
(→‎{{header|Go}}: library path update)
(→‎{{header|Go}}: added example more applicable to real world problems. for existing example, simplified one point, added an error check, output, and description)
Line 125: Line 125:


=={{header|Go}}==
=={{header|Go}}==
Example below shows simple correspondence between JSON objects and Go maps, and shows that you don't have to know anything about the structure of the JSON data to read it in.
<lang go>package main
<lang go>package main


Line 131: Line 132:


func main() {
func main() {
var data map[string]interface{}
var data interface{}
json.Unmarshal([]byte(`{"foo":1, "bar":[10, "apples"]}`), &data)
err := json.Unmarshal([]byte(`{"foo":1, "bar":[10, "apples"]}`), &data)
if err == nil {
fmt.Println(data)
fmt.Println(data)
} else {
fmt.Println(err)
}


sample := map[string]interface{}{
sample := map[string]interface{}{
Line 146: Line 151:
}
}
}</lang>
}</lang>
Output:
<pre>
map[bar:[10 apples] foo:1]
{"blue":[1,2],"ocean":"water"}
</pre>
Example below demonstrates more typical case where you have an expected correspondence between JSON data and some composite data types in your program, and shows how the correspondence doesn't have to be exact.
<lang>package main

import "encoding/json"
import "fmt"

type Person struct {
Name string `json:"name"`
Age int `json:"age,omitempty"`
Addr *Address `json:"address,omitempty"`
Ph []string `json:"phone,omitempty"`
}

type Address struct {
Street string `json:"street"`
City string `json:"city"`
State string `json:"state"`
Zip string `json:"zip"`
}

func main() {
// compare with output, note apt field ignored, missing fields
// have zero values.
jData := []byte(`{
"name": "Smith",
"address": {
"street": "21 2nd Street",
"apt": "507",
"city": "New York",
"state": "NY",
"zip": "10021"
}
}`)
var p Person
err := json.Unmarshal(jData, &p)
if err != nil {
fmt.Println(err)
} else {
fmt.Printf("%+v\n %+v\n\n", p, p.Addr)
}

// compare with output, note empty fields omitted.
pList := []Person{
{
Name: "Jones",
Age: 21,
},
{
Name: "Smith",
Addr: {"21 2nd Street", "New York", "NY", "10021"},
Ph: {"212 555-1234", "646 555-4567"},
},
}
jData, err = json.MarshalIndent(pList, "", " ")
if err != nil {
fmt.Println(err)
} else {
fmt.Println(string(jData))
}
}</lang>
Output:
<pre>
{Name:Smith Age:0 Addr:0xf840026080 Ph:[]}
&{Street:21 2nd Street City:New York State:NY Zip:10021}

[
{
"name": "Jones",
"age": 21
},
{
"name": "Smith",
"address": {
"street": "21 2nd Street",
"city": "New York",
"state": "NY",
"zip": "10021"
},
"phone": [
"212 555-1234",
"646 555-4567"
]
}
]
</pre>


=={{header|Groovy}}==
=={{header|Groovy}}==