Json to CSV parsing with raw Data

173 views
Skip to first unread message

sharath chandra

unread,
May 27, 2021, 12:48:14 PM5/27/21
to golang-nuts
The issue with Golang to retrieve raw data from Json / string variable

```
I have a Json sample message something similar with special characters 

func main() {
     msg := []byte(`{"key":"ABC\u001d\u263aDEF"}`)
     m := make(map[string]interface{})
      json.Unmarshal(msg,&m)
      ConvertToCsv(m)
}


func ConvertToCsv(m map[string]interface{}){
     buf := new(bytes.Buffer)
     for k,v := range m {
            buf.WriteString(fmt.Sprintf("%v:%v",k,v))
     }
    fmt.Println(buf.String())
 }
```

Output is similar to 

```golang
key:ABC☺DEF
```

I am expecting something similar to :
key:"ABC\\u001d\\u263aDEF"

Is this possible by any means ?

Ian Lance Taylor

unread,
May 27, 2021, 12:55:28 PM5/27/21
to sharath chandra, golang-nuts
On Thu, May 27, 2021 at 9:48 AM sharath chandra
<sharathc...@gmail.com> wrote:
>
> The issue with Golang to retrieve raw data from Json / string variable
>
> ```
> I have a Json sample message something similar with special characters
>
> func main() {
> msg := []byte(`{"key":"ABC\u001d\u263aDEF"}`)
> m := make(map[string]interface{})
> json.Unmarshal(msg,&m)
> ConvertToCsv(m)
> }
>
>
> func ConvertToCsv(m map[string]interface{}){
> buf := new(bytes.Buffer)
> for k,v := range m {
> buf.WriteString(fmt.Sprintf("%v:%v",k,v))
> }
> fmt.Println(buf.String())
> }
> ```
>
> Output is similar to
>
> ```golang
> key:ABCDEF
> ```
>
> I am expecting something similar to :
> key:"ABC\\u001d\\u263aDEF"
>
> Is this possible by any means ?

https://golang.org/pkg/strconv/#QuoteToASCII

Ian

sharath chandra

unread,
May 28, 2021, 12:26:46 PM5/28/21
to Ian Lance Taylor, golan...@googlegroups.com
QuoteToAscii converts non printable characters to \xd  , but i literally want the same value .

QuoteToAscii will not produce the json compatible string or will not escape string in true sense like 

Conversion of "abc\u001d" will be converted to "abc\x1d" which is not compatible with json string


If there is no built in cooked function ,

Can you please through some pointers how to implement on own , i am not able to figure it out ...

Manlio Perillo

unread,
May 28, 2021, 12:59:34 PM5/28/21
to golang-nuts

Also, note that the language name is Go, not Golang.


Manlio

Sean Liao

unread,
May 28, 2021, 2:00:11 PM5/28/21
to golang-nuts
maybe something like https://play.golang.org/p/z-Yp4bh7jto

Brian Candler

unread,
May 28, 2021, 6:29:30 PM5/28/21
to golang-nuts
Reply all
Reply to author
Forward
0 new messages