github.com/lmorg/murex@v0.0.0-20240217211045-e081c89cd4ef/builtins/types/json/marshal.go (about)

     1  package json
     2  
     3  import (
     4  	"github.com/lmorg/murex/lang"
     5  	"github.com/lmorg/murex/lang/types"
     6  	"github.com/lmorg/murex/utils/json"
     7  )
     8  
     9  func marshal(p *lang.Process, v interface{}) ([]byte, error) {
    10  	b, err := json.Marshal(v, p.Stdout.IsTTY())
    11  	if err == nil {
    12  		return b, err
    13  	}
    14  
    15  	if err.Error() != json.NoData {
    16  		return b, err
    17  	}
    18  
    19  	strict, _ := p.Config.Get("proc", "strict-arrays", types.Boolean)
    20  	if strict.(bool) {
    21  		return b, err
    22  	}
    23  
    24  	return []byte{'[', ']'}, nil
    25  }
    26  
    27  func unmarshal(p *lang.Process) (v any, err error) {
    28  	b, err := p.Stdin.ReadAll()
    29  	if err != nil {
    30  		return
    31  	}
    32  
    33  	err = json.Unmarshal(b, &v)
    34  
    35  	// Initially I really liked the idea of JSON files automatically falling
    36  	// back to jsonlines. However on reflection I think it is a bad idea
    37  	// because it then means we need to cover any and all instances where JSON
    38  	// is read but not calling unmarshal - which will be plentiful - else we
    39  	// end up with inconsistent and confusing behavior. But in the current
    40  	// modal all we need to do is the following (see below) so we're not
    41  	// really saving a significant amount of effort.
    42  	//
    43  	//     open ~/jsonlines.json -> cast jsonl -> format json
    44  	/*if err.Error() == "invalid character '{' after top-level value" {
    45  		// ^ this needs a test case so we catch any failures should Go ever
    46  		// change the reported error message
    47  		if jsonl, errJl := unmarshalJsonLines(b); errJl != nil {
    48  			debug.Json(err.Error(), jsonl)
    49  			return jsonl, nil
    50  		}
    51  	}*/
    52  
    53  	return
    54  }
    55  
    56  /*func unmarshalJsonLines(b []byte) (v interface{}, err error) {
    57  	var jsonl []interface{}
    58  
    59  	lines := bytes.Split(b, []byte{'\n'})
    60  	for _, line := range lines {
    61  		err = json.Unmarshal(line, &v)
    62  		if err != nil {
    63  			return nil, fmt.Errorf("Unable to unmarshal index %d in jsonlines: %s", len(jsonl), err)
    64  		}
    65  		jsonl = append(jsonl, v)
    66  	}
    67  
    68  	return jsonl, err
    69  }
    70  */