github.com/hugh712/snapd@v0.0.0-20200910133618-1a99902bd583/jsonutil/json.go (about)

     1  // -*- Mode: Go; indent-tabs-mode: t -*-
     2  
     3  /*
     4   * Copyright (C) 2017 Canonical Ltd
     5   *
     6   * This program is free software: you can redistribute it and/or modify
     7   * it under the terms of the GNU General Public License version 3 as
     8   * published by the Free Software Foundation.
     9   *
    10   * This program is distributed in the hope that it will be useful,
    11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
    12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    13   * GNU General Public License for more details.
    14   *
    15   * You should have received a copy of the GNU General Public License
    16   * along with this program.  If not, see <http://www.gnu.org/licenses/>.
    17   *
    18   */
    19  
    20  package jsonutil
    21  
    22  import (
    23  	"encoding/json"
    24  	"fmt"
    25  	"io"
    26  	"reflect"
    27  	"strings"
    28  
    29  	"github.com/snapcore/snapd/strutil"
    30  )
    31  
    32  // DecodeWithNumber decodes input data using json.Decoder, ensuring numbers are preserved
    33  // via json.Number data type. It errors out on invalid json or any excess input.
    34  func DecodeWithNumber(r io.Reader, value interface{}) error {
    35  	dec := json.NewDecoder(r)
    36  	dec.UseNumber()
    37  	if err := dec.Decode(&value); err != nil {
    38  		return err
    39  	}
    40  	if dec.More() {
    41  		return fmt.Errorf("cannot parse json value")
    42  	}
    43  	return nil
    44  }
    45  
    46  // StructFields takes a pointer to a struct and a list of exceptions,
    47  // and returns a list of the fields in the struct that are JSON-tagged
    48  // and whose tag is not in the list of exceptions.
    49  // The struct can be nil.
    50  func StructFields(s interface{}, exceptions ...string) []string {
    51  	st := reflect.TypeOf(s).Elem()
    52  	num := st.NumField()
    53  	fields := make([]string, 0, num)
    54  	for i := 0; i < num; i++ {
    55  		tag := st.Field(i).Tag.Get("json")
    56  		idx := strings.IndexByte(tag, ',')
    57  		if idx > -1 {
    58  			tag = tag[:idx]
    59  		}
    60  		if tag != "" && !strutil.ListContains(exceptions, tag) {
    61  			fields = append(fields, tag)
    62  		}
    63  	}
    64  
    65  	return fields
    66  }