Resolution for JSON parsing error “The given key was not present in the dictionary.”

While leveraging REST API, if you get the error message “The given key was not present in the dictionary.“ then it means that the request body is not being parsed correctly. For resolving this error, make sure that the Content-Type header is set to “application/json” and JSON.stringify() is called on the data value to convert it into string.

Below is a sample snippet of the script with the usage of Content-Type header and JSON.stringify to resolve such errors:

window.onload = function () {
                $.ajax({
                        url: "/OperationsManager/data/performance",
                        type: "POST",
       headers: {
                 "Content-Type": "application/json"
                },
                        data: JSON.stringify({
                        "duration":1440,
                        "id":"721BEA34-B0E4-DC97-5169-52808F731A6B",
                        "performanceCounters":[
                               {
                                       "objectname":"Health Service",
                                       "countername":"agent processor utilization",
                                       "instancename":""
                               }
                        ],
                        }),

 

This article was originally published by Microsoft's ITOps Talk Blog. You can find the original article here.