github.com/jxskiss/gopkg@v0.17.3/json/ext.go (about)

     1  package json
     2  
     3  import (
     4  	"github.com/jxskiss/gopkg/json/extparser"
     5  	"io/ioutil"
     6  	"os"
     7  )
     8  
     9  // UnmarshalExt parses the JSON-encoded data and stores the result in the
    10  // value pointed to by v.
    11  //
    12  // In addition to features of encoding/json, it enables some extended
    13  // features such as "trailing comma", "comments", "file including", etc.
    14  // The extended features are documented in the README file.
    15  func UnmarshalExt(data []byte, v interface{}, importRoot string) error {
    16  	if importRoot == "" {
    17  		wd, err := os.Getwd()
    18  		if err != nil {
    19  			return err
    20  		}
    21  		importRoot = wd
    22  	}
    23  	data, err := extparser.Parse(data, importRoot)
    24  	if err != nil {
    25  		return err
    26  	}
    27  	return Unmarshal(data, v)
    28  }
    29  
    30  // LoadExt reads JSON-encoded data from the named file at path and stores
    31  // the result in the value pointed to by v.
    32  //
    33  // In additional to features of encoding/json, it enables some extended
    34  // features such as "trailing comma", "comments", "file including" etc.
    35  // The extended features are documented in the README file.
    36  func LoadExt(path string, v interface{}, importRoot string) error {
    37  	file, err := os.Open(path)
    38  	if err != nil {
    39  		return err
    40  	}
    41  	defer file.Close()
    42  
    43  	data, err := ioutil.ReadAll(file)
    44  	if err != nil {
    45  		return err
    46  	}
    47  	return UnmarshalExt(data, v, importRoot)
    48  }