Azure Functions – The JSON parser failed: Unexpected character encountered while parsing value

If you have an Azure Function that reads from an Event Hub you might see the following error when clicking the Test/ Run button coz you are impatient and want to see what happens.

Executed ‘Functions.EventHubTrigger1’ (Failed, Id=043e8ba1-6cf2-4976-b534-f85e0107bddd, Duration=41ms)Binding parameters to complex objects (such as ‘Object’) uses Json.NET serialization.1. Bind the parameter type as ‘string’ instead of ‘Object’ to get the raw values and avoid JSON deserialization, or2. Change the queue payload to be valid json. The JSON parser failed: Unexpected character encountered while parsing value: T. Path ”, line 0, position 0.

This is because my default the Function will trigger automatically if there’s any events to process. But when you go ahead and click the Test/ Run button you are forcing the function to trigger without any input and that breaks things. The error message gives the impression you should be changing the input type to a string but that’s a whole other wroooooooong path to go (trust me, been down that!). Instead, it’s important to understand what’s really happening with this Function. Since the Function knows you are sending it Event Hub messages, and it knows these are supposed to be in JSON, it is actually helpfully parsing any input it gets as JSON. But then what do you do when you click that Test/ Run button? The portal runs the function manually and sends it the “Test Message” body.. which is obviously not JSON and so the Function borks!

I wish I had realized this last week when I was playing with Functions and spent a lot of time on this. Like an idiot I followed the error message and some GitHub issue I found and changed the input type to string. And that opened a new can of works coz now the Function wouldn’t parse the input as JSON so I had to add extra stuff like ConvertFrom-JSON … eugh, so stupid!

Anyways, hope this helps someone else from going down this path.

ps. Another thing to bear in mind- the Azure Function reads an array of JSON objects. So in the default function:

The $eventHubMessages variable is basically an array of Hash Tables (coz the Function helpfully converts the array of JSON objects to an array of Hash Tables). So that is why the next step then loops over this array to show each entry. The output is a bit confusing, so here’s two example outputs:

The function ran twice in this case. I have separated them by new lines. Each of these times it read the array of JSON objects and outputted them. Notice the output simply says System.Collections.Hashtable. That’s because ideally we should be just outputting $_ rather than "$_" :

Then you will see the correct output.