Array of bytes
nirenrc opened this issue · comments
Hello
I am trying to set array of bytes using "Set" or "SetRaw"; unfortunately it returns non array type value for specified path e.g.
- Using Set API
ba := []byte{128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 31, 32, 140}
value, _ := sjson.Set(``, "byte-array", ba)
fmt.Println(value)
Returns:
{"byte-array":"\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\u001f \ufffd"}
- Using SetRaw API:
value, _ := sjson.SetRaw(``, "byte-array", string(ba))
fmt.Println(value)
Returns:
{"byte-array":"\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\u001f \ufffd"}
appears that in either case it converts byte array into string. Unfortunately, while retrieving values using gjson returns different values
ret := gjson.Get(value, "byte-array")
fmt.Println("ret: ", ret)
Result:
ret: ������������ �
How to store byte array as pure byte array? like
{"byte-array":[127,126,125,124]}
changing type from "byte" to "uint32" or "uint16" returns result like above.
Thanking You
Niren
Hi,
SJSON stores byte[]
as a JSON string.
To store the data as an array of numbers you'll need to generate that array manually.
For example:
ba := []byte{128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 31, 32, 140}
var arr []byte
arr = append(arr, '[')
for i, c := range ba {
if i > 0 {
arr = append(arr, ',')
}
arr = strconv.AppendUint(arr, uint64(c), 10)
}
arr = append(arr, ']')
value, _ := sjson.SetRaw(``, "byte-array", string(arr))
fmt.Println(value)
Output:
{"byte-array":[128,129,130,131,132,133,134,135,136,137,138,139,31,32,140]}
Hello
ok, can be simplified by fmt.Sprint
ba := []byte{128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 31, 32, 140}
s := strings.Replace(fmt.Sprint(ba), " ", ",", -1)
value, _ := sjson.SetRaw(``, "byte-array", s)
fmt.Println(value)
Storing []byte as string is ok, it just gjson returns incorrect data. I did not try converting back to "[]byte".
Thanking You
Niren
You're welcome. I'm closing this issue, but feel free to reopen if needed.