Thursday, April 18, 2019

Go handle Json Perfectly

JSON abbreviation "JavaScript Object Notation". There're so many tools for structure data such as xml, Json, asn.1 and google protobuf.

XML and JSON:
writing code in a xml, so called boilerplate. Java and android use xml for project management. While json, is easy as compare to xml. Mostly use json because it's easy to play around and good choice for web application.

Code :
package main
import ( "fmt" "encoding/json")
type Books struct{ Title string  Status bool Writer string  Comments string}


func main() { var Library =[]Books{ {Title:"Lord of Rings the fellowship", Status:false, Writer:"J-J-R-Tolkien",Comments:""}, {Title:"Quantum Aspects of Life",Status: false, Writer:"Paul-C",Comments:""}, {Title:"You were born rich", Status:true, Writer:"Bob Proctor",Comments:"good book"}, } if lib , err := json.MarshalIndent(&Library,""," "); err== nil{ fmt.Printf("%s",lib) } }
Encode library provide so many sub packages json one of them, try to use it the above it just show you a demonstration. You can use Marshal or MarshalIndent for encoding your data in json.

Marshal and MarshalIndent:
  Marshal :
            lib,err := json.Marshal(Library)
        Marshal take a parameter that to be convert in my case that is Library. Json.Marshal
return value and error so you can handle it. This function have one problem encoded data are  not distinguishable. Return value similar to string. 

MarshalIndent:
           lib, err := json.MarshalIndent(&Library, "", " ")
 Again this is similar to previous function but , this function demand address of data , not itself. Second it take two parameters . Just play around

Similar like encoding, you can also decode data by using unMarshal and unMarshalIndent.

I'm thinking i will add google protobuf in my upcoming articles.

 



                                                                              



No comments:

Post a Comment

Do you support us?

Business address
0x1D24D8f27ea73ff604C7685246bdC6ae55bddaEF

Unheard thousand whispered

  No nation stands tall without appreciating the sacrifices of women. Women do so much more than just bear children and manage households. M...

Achieves