How to convert a JSON string into an object/array

By default, Formstack Documents accepts JSON via Webhook and API integrations; however, if you are attempting to merge a JSON string, you may find that the merge data does not format nicely into an object or an array.  For instance, consider the example below:

jsonString.png

As you can see, the data that is being passed into the "Contact" field appears to be a valid JSON object; however, because it was sent as a string, Formstack Documents does not know to interpret it as an object.

Luckily, by utilizing Formstack Documents' Field Map feature and some built-in PHP functions, we can transform this data into something more meaningful.

First, you will need to ensure that your document has the Field Map setting enabled:

  1. From the template, select the Settings tab.
  2. In the right pane of the Settings tab, click on the Advanced Settings option.
  3. Enable the option to Use Field Map for custom integrations.
  4. Click Save Settings.

Next, we will configure the Field Map:

  1. Navigate to the Field Map tab.
  2. Find the field in question (in this example, it would be "Contact") and enter in a variation of the following code:
    {$_Placeholder = json_decode($OriginalField, true)}{json_encode($_Placeholder)}
    • $_Placeholder is a new variable/merge field that we will use to store the decoded JSON string.  This can be replaced with whatever name you would like, but we would typically recommend prefixing an underscore to the name of the original field (e.g., if your field's name is "Contact", then this variable could be renamed to "$_Contact").
    • $OriginalField is the name of the original merge field (e.g., the example above, we would want to rename this to "$Contact").
    • json_decode is a PHP method that converts the string into a PHP variable, while json_encode returns a string in the proper format that Formstack Documents can recognize.
  3. Following the example above, the field should now look something like this:
    mceclip0.png
  4. Click Save Field Map.

After you have configured the field map, you are now ready to test the merge.  Assuming that the JSON being passed in is valid, you should now see something like this in the merge data after your next merge:

mceclip1.png

 

Was this article helpful?
3 out of 3 found this helpful

Comments

0 comments

Article is closed for comments.