github.com/qri-io/qri@v0.10.1-0.20220104210721-c771715036cb/base/toqtype/toqtype.go (about)

     1  package toqtype
     2  
     3  // TODO(dlong): Utilities for creating qtype values. Will likely rename or move this soon.
     4  
     5  import (
     6  	"encoding/csv"
     7  	"encoding/json"
     8  	"strings"
     9  )
    10  
    11  // StructToMap converts any struct into a corresponding map with string keys for each field name
    12  func StructToMap(value interface{}) (map[string]interface{}, error) {
    13  	var result map[string]interface{}
    14  	bytes, err := json.Marshal(value)
    15  	if err != nil {
    16  		return nil, err
    17  	}
    18  	err = json.Unmarshal(bytes, &result)
    19  	if err != nil {
    20  		return nil, err
    21  	}
    22  	return result, nil
    23  }
    24  
    25  // MustParseJSONAsArray parses the string as a json array, or panics. Should only use in tests
    26  func MustParseJSONAsArray(content string) []interface{} {
    27  	var result []interface{}
    28  	err := json.Unmarshal([]byte(content), &result)
    29  	if err != nil {
    30  		panic(err)
    31  	}
    32  	return result
    33  }
    34  
    35  // MustParseCsvAsArray parses the string as a json array, or panics. Should only use in tests
    36  func MustParseCsvAsArray(content string) []interface{} {
    37  	r := strings.NewReader(content)
    38  	rows, err := csv.NewReader(r).ReadAll()
    39  	if err != nil {
    40  		panic(err)
    41  	}
    42  	result := make([]interface{}, 0, len(rows))
    43  	for _, row := range rows {
    44  		result = append(result, row)
    45  	}
    46  	return result
    47  }