How to send a text property to API using Json?

Hello, I’m creating an API and trying to send this JSON body using POST to my route.

{
    "announcement": {
        "title": "Title sample",
        "content": "Quisquam ullam neque. Magni et fuga in facere incidunt. Impedit inventore voluptates explicabo corporis assumenda voluptatum fugit reiciendis soluta. Porro officia libero. Iste doloremque accusantium nulla voluptatem similique vero. Sunt voluptate commodi earum quisquam reiciendis quisquam pariatur placeat.
Voluptatum quos molestiae repellendus. Rem eius aliquid magnam praesentium optio. Numquam hic omnis deleniti quasi inventore magni alias distinctio. Maiores cum iure eum et illo nesciunt.
Voluptatum voluptatum vel vero sapiente. Quos libero eligendi totam. Consectetur voluptate illo autem nisi ullam. Vero quos recusandae quidem voluptate quo excepturi sed. Ipsum qui libero consequatur quam beatae. Assumenda iste perspiciatis nam commodi quisquam quasi nemo mollitia."
    }
}

I’m receiving this error and can’t figure out what I should configure to my route accept or convert correctly:

(Plug.Parsers.ParseError) malformed request, a Jason.DecodeError exception was raised with message "unexpected byte at position 392: 0xA (\"\\n\")"

Someone can explain where I’m making a mistake?
Thank you!

Newlines inside values in JSON need to be properly escaped to \n. For instance, Jason does this:

iex(7)> long = """  
...(7)> first_line 
...(7)> second_line
...(7)> third_line 
...(7)> """       
"first_line\nsecond_line\nthird_line\n"

iex(8)> IO.puts Jason.encode!(%{"foo" => long}) 
{"foo":"first_line\nsecond_line\nthird_line\n"}

1 Like

Oh I got this, but my data even not reach controller. Beucase of that I can’t encode.
Maybe I should configure something before to reach controller?

You need to fix the data where it’s coming from, not in Phoenix:

  • if you’re using a tool like Postman to send a request it needs to be fixed in that tool
  • if you’re sending that request from another piece of code, you need to fix that code because it’s producing broken JSON
2 Likes

Humm ok, I got it!
Thank you, everything makes sense right now for me.