2

When I try to run given code I get the error :: string literal not terminated (illegal character U+005C '\') . How do I fix the given code?

payload := "{
    \"key_id\":\"3\",
    \"contacts\":[
        {
            \"external_id\":\"chandan4u1990@gmail.com\",
            \"data\":{
                \"global\":{
                    \"name\":\"Adoni Mishra\"
                }
            }
        },
        {
            \"external_id\":\"chandankumarc@airasia.com\",
            \"data\":{
                \"global\":{
                    \"name\":\"CHANDAN KUMAR\"
                }
            }
        }
    ]
}"

When I concat all the lines in one then it starts working::

payload := "{\"key_id\":\"3\",\"contacts\":[{\"external_id\":\"chandan4u1990@gmail.com\",\"data\":{\"global\":{\"name\":\"Adoni Mishra\"}}},{\"external_id\":\"chandankumarc@airasia.com\",\"data\":{\"global\":{\"name\":\"CHANDAN KUMAR\"}}}]}"
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Chandan Kumar
  • 799
  • 7
  • 23

1 Answers1

2

You are using an interpreted string literal which may not contain newlines! Spec: String literals:

Interpreted string literals are character sequences between double quotes, as in "bar". Within the quotes, any character may appear except newline and unescaped double quote.

Use a raw string literal so you don't even have to escape quotes, it will be much more readable, and newlines are allowed in raw string literals:

Raw string literals are character sequences between back quotes, as in foo. Within the quotes, any character may appear except back quote.

For example:

    payload := `{
    "key_id":"3",
    "contacts":[
        {
            "external_id":"chandan4u1990@gmail.com",
            "data":{
                "global":{
                    "name":"Adoni Mishra"
                }
            }
        },
        {
            "external_id":"chandankumarc@airasia.com",
            "data":{
                "global":{
                    "name":"CHANDAN KUMAR"
                }
            }
        }
    ]
}`

You can also put everything in one line if you don't need indentation:

payload := `{"key_id":"3","contacts":[{"external_id":"chandan4u1990@gmail.com","data":{"global":{"name":"Adoni Mishra"}}},{"external_id":"chandankumarc@airasia.com","data":{"global":{"name":"CHANDAN KUMAR"}}}]}`

Try it on the Go Playground.

icza
  • 389,944
  • 63
  • 907
  • 827
  • If I convert given formate in bytes result are different – Chandan Kumar May 24 '19 at 07:46
  • @ChandanKumar Yes, because your working "one-line" string has no newlines and indentation, but those have no meaning in JSON, it represents the same data. And you can remove newlines and spaces from raw string literals too, see edited answer. – icza May 24 '19 at 07:48