Home > Backend Development > Golang > golang handles json comments

golang handles json comments

王林
Release: 2023-05-15 09:33:07
Original
672 people have browsed it

During the golang development process, we often encounter situations where json needs to be processed. However, the processing of comments in json is a very troublesome problem. Using comments in json files can help developers better understand and maintain the code, but the standard json library does not support comments. So, how to solve this problem?

1. The golang standard library cannot handle json comments

The first thing you need to understand is that the standard golang json library cannot handle comments in json, even if we add comments in json, use json The .Unmarshal() function cannot be parsed either. Therefore, we need to find other solutions to solve this problem.

2. Third-party libraries

By searching, we can find some third-party libraries, such as: encorehu/json-annotate, jbarratt/jsonparser or pebbe/util, etc., they can all support processing json annotations, but they may be cumbersome to use and require encapsulation or secondary development by yourself.

3. Custom parser

The third method is to use a custom parser. You can write your own parser to process comments in the json file. This method is the most flexible and can be customized according to actual needs.

The following is a sample code for using golang custom parser to parse json files containing comments:

package main

import (
    "bufio"
    "fmt"
    "io"
    "os"
    "unicode"
)

type JsonScanner struct {
    r *bufio.Reader
}

func NewJsonScanner(r io.Reader) *JsonScanner {
    return &JsonScanner{
        r: bufio.NewReader(r),
    }
}

func (s *JsonScanner) read() (rune, error) {
    char, _, err := s.r.ReadRune()
    return char, err
}

func (s *JsonScanner) unread() error {
    return s.r.UnreadRune()
}

func (s *JsonScanner) Scan() (string, error) {
    var c rune
    var err error
    var token []rune
    var inComment bool

    for {
        c, err = s.read()
        if err != nil {
            break
        }

        if !inComment {
            if unicode.IsSpace(c) || c == ',' || c == ':' || c == '{' || c == '}' || c == '[' || c == ']' || c == '"' {
                if err = s.unread(); err != nil {
                    break
                }
                break
            }
        }

        token = append(token, c)

        if c == '/' {
            nextChar, err := s.read()
            if err == nil && nextChar == '/' {
                inComment = true
            } else {
                err = s.unread()
                break
            }
        } else if c == '
' {
            inComment = false
        }
    }

    if inComment {
        return "", fmt.Errorf("comment not closed")
    }

    return string(token), err
}

func parseJson(r io.Reader) error {
    scanner := NewJsonScanner(r)

    for {
        token, err := scanner.Scan()
        if err == io.EOF {
            break
        } else if err != nil {
            return err
        }

        fmt.Println(token)
    }

    return nil
}

func main() {
    f, _ := os.Open("test.json")
    defer f.Close()

    if err := parseJson(f); err != nil {
        fmt.Printf("parseJson error: %v
", err)
    }
}
Copy after login

4. Comment rules

Although the custom parser can process comments, But we also need to specify some annotation rules to make it more convenient to write and maintain json files containing annotations. Here is a reference to some comment rules:

  1. Single-line comments begin with "//" and end at the end of the line.

    {
    "name": "test", // 名称
    "age": 22 // 年龄
    }
    Copy after login
  2. Multi-line comments start with "/" and end with "/".

    {
    "name": "test", /* 名称 */
    "age": 22 /* 年龄 */
    }
    Copy after login
  3. Comments can appear anywhere that are not strings, numbers, and Boolean values.
  4. 4. Summary

    It may be troublesome to process json files containing comments in golang, but we can use third-party libraries or custom parsers to solve this problem. Custom parsers can achieve the most flexible processing, but require additional development costs. Annotation rules also need to be standardized for better application.

    The above is the detailed content of golang handles json comments. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template