github.com/lmorg/murex@v0.0.0-20240217211045-e081c89cd4ef/docs/apis/Unmarshal.md (about) 1 # `Unmarshal()` (type) 2 3 > Converts a structured file format into structured memory 4 5 ## Description 6 7 This is a function you would write when programming a Murex data-type. 8 The unmarshal function takes in a byte slice and returns a Go (golang) 9 `type` or `struct` or an error. 10 11 This unmarshaller is then registered to Murex inside an `init()` function 12 and Murex builtins can use that unmarshaller via the `UnmarshalData()` 13 API. 14 15 ## Usage 16 17 Registering `Unmarshal()` (for writing builtin data-types) 18 19 ```go 20 // To avoid data races, this should only happen inside func init() 21 lang.Unmarshallers[ /* your type name */ ] = /* your readIndex func */ 22 ``` 23 24 Using an existing unmarshaller (eg inside a builtin command) 25 26 ```go 27 // See documentation on lang.UnmarshalData for more details 28 v, err := lang.UnmarshalData(p *lang.Process, dataType string) 29 ``` 30 31 ## Examples 32 33 Defining a marshaller for a murex data-type 34 35 ```go 36 package example 37 38 import ( 39 "encoding/json" 40 41 "github.com/lmorg/murex/lang" 42 ) 43 44 func init() { 45 // Register data-type 46 lang.Unmarshallers["example"] = unmarshal 47 } 48 49 // Describe unmarshaller 50 func unmarshal(p *lang.Process) (interface{}, error) { 51 // Read data from STDIN. Because JSON expects closing tokens, we should 52 // read the entire stream before unmarshalling it. For formats like CSV or 53 // jsonlines which are more line based, we might want to read STDIN line by 54 // line. However given there is just one data return, you still effectively 55 // head to read the entire file before returning the structure. There are 56 // other APIs for iterative returns for streaming data - more akin to the 57 // traditional way UNIX pipes would work. 58 b, err := p.Stdin.ReadAll() 59 if err != nil { 60 return nil, err 61 } 62 63 var v interface{} 64 err = json.Unmarshal(b, &v) 65 66 // Return the Go data structure or error 67 return v, err 68 } 69 ``` 70 71 ## Parameters 72 73 1. `*lang.Process`: Process's runtime state. Typically expressed as the variable `p` 74 75 ## See Also 76 77 * [apis/`Marshal()` (type)](../apis/Marshal.md): 78 Converts structured memory into a structured file format (eg for stdio) 79 * [apis/`lang.MarshalData()` (system API)](../apis/lang.MarshalData.md): 80 Converts structured memory into a Murex data-type (eg for stdio) 81 * [apis/`lang.UnmarshalData()` (system API)](../apis/lang.UnmarshalData.md): 82 Converts a Murex data-type into structured memory 83 84 <hr/> 85 86 This document was generated from [lang/define_unmarshal_doc.yaml](https://github.com/lmorg/murex/blob/master/lang/define_unmarshal_doc.yaml).