golang tutorial - Sample Json File | Json In Golang - golang - go programming language - google go - go language - go program - google language



Sample Json File

  • JavaScript Object Notation or JSON is an open-standard file format that uses human-readable text to transmit data objects consisting of attribute-value pairs and array data types.
  • It is a very common data format used for asynchronous browser/server communication, including as a replacement for XML in some AJAX-style systems.
 regular expressions
  • JSON is a language-independent data format. It was derived from JavaScript.
  • The official Internet media type for JSON is application/json.
  • JSON filenames use the extension .json.

JSON Example

  • JSON representation describing a person
{
  "firstName": "John",
  "lastName": "Smith",
  "isAlive": true,
  "age": 25,
  "address": {
    "streetAddress": "21 2nd Street",
    "city": "New York",
    "state": "NY",
    "postalCode": "10021-3100"
  },
  "phoneNumbers": [
    {
      "type": "home",
      "number": "212 555-1234"
    },
    {
      "type": "office",
      "number": "646 555-4567"
    },
    {
      "type": "mobile",
      "number": "123 456-7890"
    }
  ],
  "children": [],
  "spouse": null
}
click below button to copy the code. By - golang tutorial - team

JSON Schema

  • JSON Schema specifies a JSON-based format to define the structure of JSON data for validation, documentation, and interaction control.
  • It provides a contract for the JSON data required by a given application, and how that data can be modified.
  • JSON Schema is based on the concepts from XML Schema (XSD), but is JSON-based.
  • As in XSD, the same serialization/deserialization tools can be used both for the schema and data; and is self-describing.
 regular expressions

JSON Schema Example

{
  "$schema": "http://json-schema.org/schema#",
  "title": "Product",
  "type": "object",
  "required": ["id", "name", "price"],
  "properties": {
    "id": {
      "type": "number",
      "description": "Product identifier"
    },
    "name": {
      "type": "string",
      "description": "Name of the product"
    },
    "price": {
      "type": "number",
      "minimum": 0
    },
    "tags": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "stock": {
      "type": "object",
      "properties": {
        "warehouse": {
          "type": "number"
        },
        "retail": {
          "type": "number"
        }
      }
    }
  }
}
click below button to copy the code. By - golang tutorial - team

The JSON Schema above is used to test the validity of the JSON code below:

{
  "id": 1,     // required field specified in the schema
  "name": "wikitechy",   // required field specified in the schema
  "price": 123,           // required field specified in the schema
  "tags": [
    "go programming language",
    "angularjs tutorials"
  ],
  "stock": {
    "warehouse": 300,              // type is number specified in the schema
    "retail": 20		// type is number specified in the schema
  }
}
click below button to copy the code. By - golang tutorial - team
package main

// imported the specific libraries needed for json object
	import "encoding/json"
import "fmt"
import "os"
// We’ll use these two structs to demonstrate encoding and decoding of custom types below.
	type Response1 struct {
    Page   int
    Tutorials []string
}
type Response2 struct {
    Page   int      `json:"page"`
    Tutorials []string `json:"tutorials"`
}

	func main() {
// First we’ll look at encoding basic data types to JSON strings. Here are some examples for atomic values.
	    bolB, _ := json.Marshal(true)
    fmt.Println(string(bolB))

	    intB, _ := json.Marshal(1)
    fmt.Println(string(intB))

	    fltB, _ := json.Marshal(2.34)
    fmt.Println(string(fltB))

	    strB, _ := json.Marshal("gopher")
    fmt.Println(string(strB))
// And here are some for slices and maps, which encode to JSON arrays and objects as you’d expect.
	    slcD := []string{"HTML tutorials", "angularjs language tutorials", "Go language tutorials"}
    slcB, _ := json.Marshal(slcD)
    fmt.Println(string(slcB))

	    mapD := map[string]int{"HTML tutorials": 5, "css tutorials": 7}
    mapB, _ := json.Marshal(mapD)
    fmt.Println(string(mapB))
// The JSON package can automatically encode your custom data types. It will only include exported fields in the encoded output and will by default use those names as the JSON keys.
	    res1D := &Response1{
        Page:   1,
        Tutorials: []string{"HTML tutorials", "angularjs language tutorials", "Go language tutorials"}}
    res1B, _ := json.Marshal(res1D)
    fmt.Println(string(res1B))
// You can use tags on struct field declarations to customize the encoded JSON key names. Check the definition of Response2 above to see an example of such tags.
	    res2D := &Response2{
        Page:   1,
        Tutorials: []string{"HTML tutorials", "angularjs language tutorials", "Go language tutorials"}}
    res2B, _ := json.Marshal(res2D)
    fmt.Println(string(res2B))
// Now let’s look at decoding JSON data into Go values. Here’s an example for a generic data structure.
	    byt := []byte(`{"num":6.13,"strs":["a","b"]}`)
// We need to provide a variable where the JSON package can put the decoded data. This map[string]interface{}will hold a map of strings to arbitrary data types.
	    var dat map[string]interface{}
// Here’s the actual decoding, and a check for associated errors.
	    if err := json.Unmarshal(byt, &dat); err != nil {
        panic(err)
    }
    fmt.Println(dat)

	    
//In order to use the values in the decoded map, we’ll need to cast them to their appropriate type. For example here we cast the value in num to the expected float64 type.

num := dat["num"].(float64)
    fmt.Println(num)
// Accessing nested data requires a series of casts.
	    strs := dat["strs"].([]interface{})
    str1 := strs[0].(string)
    fmt.Println(str1)
// We can also decode JSON into custom data types. This has the advantages of adding additional type-safety to our programs and eliminating the need for type assertions when accessing the decoded data.
	    str := `{"page": 1, "tutorials": ["HTML tutorials", "angularjs language tutorials"]}`
    res := Response2{}
    json.Unmarshal([]byte(str), &res)
    fmt.Println(res)
    fmt.Println(res.Tutorials[0])
// In the examples above we always used bytes and strings as intermediates between the data and JSON representation on standard out. We can also stream JSON encodings directly to os.Writers like os.Stdout or even HTTP response bodies.
	    enc := json.NewEncoder(os.Stdout)
    d := map[string]int{"HTML tutorials": 5, "css tutorials": 7}
    enc.Encode(d)
}
click below button to copy the code. By - golang tutorial - team
 regular expressions
golang , gopro , google go , golang tutorial , google language , go language , go programming language

Output for the above go programming language

$ go run json.go
true
1
2.34
"gopher"
["HTML tutorials","angularjs language tutorials","Go language tutorials"]
{"HTML tutorials":5,"css tutorials":7}
{"Page":1,"Tutorials":["HTML tutorials","angularjs language tutorials","Go language tutorials"]}
{"page":1,"tutorials":["HTML tutorials","angularjs language tutorials","Go language tutorials"]}
map[num:6.13 strs:[a b]]
6.13
a
{1 [HTML tutorials angularjs language tutorials]}
HTML tutorials
{"HTML tutorials":5,"css tutorials":7}

Related Searches to Json In Golang