Golang reads JSON files (Reading Notes)

Source: Internet
Author: User

JSON (JavaScript Object Notation) is a more lightweight data exchange format than XML. It is easy for people to read and write, and easy for program parsing and generation. Although JSON is a subset of JavaScript, JSON uses a text format completely independent of programming languages and is represented in the text description form of key/value (similar to map in go ), this makes it an ideal cross-platform, cross-language data exchange language. I remember that when I first came into contact with the JSON data format, I was very impressed with the ease of processing on the JS page. Later, I learned something about MongoDB to fully process the data in this format. In the past, I personally did not like this type of key-value pair data, because I always felt that this underlying layer may be more convenient to map. However, in many cases, this form is indeed indispensable.

The Go language provides built-in support for JSON. With the go language's built-in encoding/JSON standard library, developers can easily use the go program to generate and parse data in JSON format.


For example:

Package mainimport ("encoding/JSON" "FMT") type book struct {Title string author [] string publisher string price float64 ispublished bool} func main () {B: = [] Byte ('{"title": "Go Programming Language", "author": ["John", "ADA", "Alice"], "publisher ": "Qinghua", "ispublished": True, "price": 99} ') // create a target instance object to store the decoded value var book err: = JSON. unmarshal (B, & book) If Err! = Nil {FMT. println ("error in translating,", Err. Error () return} FMT. println (book. Author )}

The JSON. unmarshal () function searches for fields in the target structure in the agreed order. If one field is found, it matches. These fields must start with an uppercase letter and be exported in the type declaration.

But what if the data structure in JSON data does not match the target type in go? If the field in JSON does not exist in the go target type, the JSON. unmarshal () function discards the field during decoding. This feature allows us to filter the specified value from a piece of JSON data and fill it into multiple go language types. Of course, the premise is that the field structure of JSON data is known. This also means that private fields (not capitalized) that cannot be exported in the target type will not be affected by resolution conversion,

If you want to parse a configuration file, in order to make the changes at the program end flexible, most of the time you don't know what structure the configuration file is in, you just need to retrieve it as needed. The Go language supports interfaces. In go, an interface is a combination of predefined methods. Any type can be implemented by a predefined method of the interface without the need to display a declaration, therefore, no empty interface of any method represents any type. In other words, each type actually implements at least one empty interface. The flexible type system built in go conveys a valuable message: the empty interface is a common type. To parse a piece of JSON with an unknown structure, you only need to decode the JSON data and output it to an empty interface. In the go standard library encoding/JSON package, values of the map [String] interface {} and [] interface {} types can be used to store JSON objects or arrays of unknown structures respectively.

In the previous example, We just removed the struct and changed it into an unknown structure.

Package mainimport ("encoding/JSON" "FMT") func main () {B: = [] Byte ('{"title": "Go Programming Language", "author ": ["John", "ADA", "Alice"], "publisher": "Qinghua", "ispublished": True, "price": 99 }') // create a target instance object to store the decoded value var inter interface {} err: = JSON. unmarshal (B, & Inter) If Err! = Nil {FMT. println ("error in translating,", err. error () return} // to access the decoded data structure, you must first determine whether the target structure is the expected data type book. OK: = Inter. (Map [String] interface {}) // then access the decoded target data through the for loop if OK {for K, V: = range book {Switch Vt: = v. (type) {Case float64: FMT. println (k, "Is float64", Vt) Case string: FMT. println (k, "is string", Vt) case [] interface {}: FMT. println (k, "is an array:") for I, IV: = range VT {FMT. println (I, IV)} default: FMT. println ("illegle type ")}}}}

To be honest, this conversion is really complicated, but it is also a way to parse JSON data of unknown structures.

In the past, I tried to use XML for configuration files. However, in that case, I had to know which data items (KEYS) were available. However, for flexible configuration files, there was no way to predict which items were included, when each module needs data, it only needs to extract it from the public information, and the main program does not need to know which information is public, it only needs to save the message as a key-value pair for the subroutine to call.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.