Last Updated: September 03, 2019
·
17.28K
· bjacog

Adding comments to JSON

There is no comment notation available in JSON. So in order not to break the response with a nasty print_r or echo, we can simply include the output we want as one of the objects/items of the JSON object.

Consider the snippet below:

{"13":
    {
        "monthly_raw":614.20956851334,
        "weekly_raw":141.39219818688,
        "monthly_formatted":"$     614.21",
        "weekly_formatted":"$ 141.39",
        "debug_comment":"select monthly_raw from payment_tables 
         where user_id = 999 and 
       some_other_debug_value = 7 limit 1"}
}

This is quite handy for debugging larger requests.
Obviously these shouldn't make it to production as they add to the amount of data returned by the request.

3 Responses
Add your response

Normally JSON is not typed but generated by functions/methods. Better give comment on those.

over 1 year ago ·

In this scenario, a comment in the code would not have helped me debug the response, I needed to see the query that was ran to generate the json. This way made it nice and readable in chrome's console and as a bonus it didn't mess up the user experience.

over 1 year ago ·

This is a great example since it's multiline, shows code/sql being treated as text, and obviously a user-chosen key so people don't think they must use 'debug_comment' and nothing else.as some sort of comment magic word. Thanks!!

over 1 year ago ·