Home > Software engineering >  Unexpected JSON format returned by API
Unexpected JSON format returned by API

Time:08-01

I am working with a third party API that I do not have any control over, and the only documentation is a URL to perform the request. When examining the response, I see an unusual format containing newline characters and line breaks:

{"history":["1.) 01- AUTHOR - TOPIC \/ DATE\n
","2.) Author Topic  (May-2022)\n
","18.) Author Topic  (July-2022)\n
","19.) Author Topic 2021\n
"],"title":"Author email topic (June-2022)","art":"https:\/\/some_url.com\/cp\/library\/image.png","ulistener":"10","listeners":"2","bitrate":"128","djusername":"No DJ","djprofile":"https:\/\/some_url.com\/cp\/musiclibrary\/nodj.png"},

This looks like a nightmare to try and parse into conventional JSON. I am new to working with JSON and have not encountered this before. Is there any way to work with this without first running it through a script to remove the newlines and other unexpected characters?

It may be worth noting that the API endpoint appears to be running some PHP code: https://some_url/cp/get_info.php?p=1234

CodePudding user response:

Escaped newlines inside JSON strings are totally valid within the JSON spec. This should parse just fine using any compliant JSON parser. It will just result in strings that end in new lines - which can be a headache to deal with, but aren't really a parsing problem so much as a post parsing data sanitation problem. Good old JSON.parse (or your language's equivalent) should handle this just fine.

  • Related