The Zendesk REST API is a JSON API. If you want to send data to the API to update or create data in your Zendesk product, you need to convert it to JSON first. If you want to get data from your Zendesk product, the API will deliver it as JSON and you'll need to convert it to something you can use.
This article covers the following topics:
- JSON basics
- Converting JSON to data you can understand
- Converting JSON to data your code understands
- Converting data in your code to JSON
- Using JSON in cURL statements
JSON basics
JSON is a lightweight data-interchange format that's easy for humans to read and machines to parse. Example:
{
"posts": [
{
"id": 35467,
"title": "How do I open the safe",
...
},
...
]
}
JSON data typically consists of one or more named properties, such as the "posts"
property above. The property's value in this case is a list of post objects. Each of the objects shares a set of properties, such as "id"
, "title"
, and others .
JSON data can be structured in many different ways. Example:
{
"vote": {
"id": 35467,
"user_id": 888887,
"value": -1,
...
}
}
See the API documentation for the various API endpoints to learn the structure of the JSON data they return.
To learn more about JSON, see Introducing JSON on the json.org site.
Converting JSON to data you can understand
The API returns JSON on a single line. If it only has a few properties, you can read it easily enough. Pasting it into a text editor and manually inserting line breaks helps.
If the JSON contains multiple objects with lots of properties, the information becomes more challenging to read:
One solution is to pretty print the information. A Google search returns a number of solutions. The simplest in terms of setup is the "JSON Formatter" extension for Google Chrome. You can get it from https://chrome.google.com/webstore/detail/json-formatter/bcjindcccaagfpapjjmafapmmgkkhgoa?hl=en . After installing it, in Chrome select Windows > Extensions , and select the "Allow access to file URLs" option for the JSON Formatter extension. This enables pretty printing local files.
Paste your JSON results to a text file and save it with a .txt extension. Then open the file in Chrome ( File > Open File ).
Converting JSON to data your code understands
If you want to use the JSON returned by the API in your code, you have to convert it into a data structure your code understands. Most programming languages have tools to help.
This article covers JavaScript, Python, and Perl. If you don't use these languages, a quick search in your language's documentation should uncover equivalent tools.
JavaScript
Use the JSON.parse()
method in JavaScript to convert JSON strings into JavaScript objects.
To give the method a test run, paste the following snippet in your browser's JavaScript console and press Enter:
var json_string = '{"article":{"title":"Great Expectations"}}';
var js_object = JSON.parse(json_string);
console.log(typeof js_object);
console.log(js_object.article.title);
Note : To access the console in Chrome, select View > Developer > JavaScript Console . In Firefox, select Tools > Web Developer > Web Console , and look for the entry field at the bottom of the console. If you get a scam warning when pasting the snippet, type "allow pasting" in the field and try again.
The script should print the following lines in the console:
object
Great Expectations
The first line tells you the data is now contained in a JavaScript object. The second line displays the value of the article.title
property.
To learn more, see JSON.parse() in the MDN documentation.
Python 3
Python's built-in json library converts JSON strings or files into Python data structures.
Use json.loads()
to convert JSON strings:
import json
json_string = '{"article":{"title":"Great Expectations"}}'
python_data = json.loads(json_string)
print(type(python_data))
print(python_data['article']['title'])
Running this code in a command line interface should print the following lines:
<class 'dict'>
Great Expectations
The first line tells you the data is now contained in a Python dictionary. The second line displays the value of the title
property.
Use json.load()
(singular) to convert files that contain JSON:
import json
with open('json.txt', mode='r', encoding='utf-8') as f:
python_data = json.load(f)
print(type(python_data))
To learn more about these methods, see the json module documentation on the Python website.
To learn how to use Python to make API requests that return JSON data, see the REST API tutorial for Python .
If you use the popular Requests package , you can use the response
object's json()
method to convert the JSON returned in HTTP responses. Example:
import requests
...
response = requests.get(url, credentials)
python_data = response.json()
See the REST API tutorial for Python for details.
You can also use the json.loads()
method with the Requests library, but make sure to pass only the response content, not the whole response. HTTP responses contain other information such as headers that will cause errors. In the Requests API, the response content is contained in the the response
object's text
property. Example:
import json
import requests
...
response = requests.get(url, credentials)
python_data = json.loads(response.text)
See the response object API doc on the Requests website for more information.
Perl
Use the decode()
method in the JSON module on CPAN to convert JSON strings into Perl data structures. Download and install the module from CPAN. See these instructions to install it.
Decoding example:
use strict;
use warnings;
use JSON;
my $json_string = '{"article":{"title":"Great Expectations"}}';
my $json = JSON->new->utf8;
my $perl_data = $json->decode($json_string);
print ref($perl_data) . "\n";
print $perl_data->{'article'}{'title'} . "\n";
Running this code in a command line interface should print the following lines:
HASH
Great Expectations
The first line tells you the data is now contained in a Perl hash. The second line displays the value of the title
property.
To learn more about the decode()
method, see the JSON module documentation on CPAN.
To learn how to use Perl to make API requests that return JSON data, see the REST API tutorial for Perl .
Converting data in your code to JSON
If you want to use data in your code to update or create data in a Zendesk product, you need to convert it to JSON before sending it with the API request.
This article covers JavaScript, Python, and Perl. If you don't use these languages, you should find the equivalent in your language's documentation.
JavaScript
Use the JSON.stringify()
method in JavaScript to convert JavaScript objects to JSON strings.
To give the method a test run, paste the following snippet in your browser's JavaScript console and press Enter:
var js_object = {ticket: {comment: {body: "The smoke is very colorful." }}};
var json_string = JSON.stringify(js_object);
console.log(typeof json_string);
console.log(json_string);
Note : To access the console in Chrome, select View > Developer > JavaScript Console . In Firefox, select Tools > Web Developer > Web Console , and look for the entry field at the bottom of the console. If you get a scam warning when pasting the snippet, type "allow pasting" in the field and try again.
The script should print the following lines in the console:
string
{"ticket":{"comment":{"body":"The smoke is very colorful."}}}
The first line tells you the data is now a string and the second line displays the JSON.
To learn more, see JSON.stringify() in the MDN documentation.
Python 3
Use the json.dumps()
method in the Python json library to convert Python data into JSON. Example:
import json
python_data = {'ticket': {'comment': {'body': 'The smoke is very colorful.'}}}
json_string = json.dumps(python_data)
print(type(json_string))
print(json_string)
Running this code in a command line interface should print the following lines:
<class 'str'>
{"ticket":{"comment":{"body":"The smoke is very colorful."}}}
The first line tells you the data is now a string and the second line displays the JSON.
To learn more about the json.dumps()
method, see the json module documentation on the Python website.
To learn how to use Python to make API requests containing JSON data, see the REST API tutorial for Python .
Pretty printing the JSON
You can also use json.dumps()
to pretty print the JSON. Simply add an argument named indent
to the json.dumps()
method, as follows:
json_string = json.dumps(python_data, indent=2)
The example should now print:
{
"ticket": {
"comment": {
"body": "The smoke is very colorful."
}
}
}
Writing the JSON to a file
You can write the JSON to a new file named json.txt with the following lines:
with open('json.txt', mode='w', encoding='utf-8') as f:
f.write(json_string)
See Using JSON in cURL requests to use JSON files in cURL requests.
Perl
Use the encode()
method in the JSON module on CPAN to convert Perl data structures into JSON strings. Download and install the module from CPAN. See these instructions to install it.
Encoding example:
use strict;
use warnings;
use JSON;
my %perl_data = (ticket => { comment => { body => 'The smoke is very colorful.' }});
my $json = JSON->new;
my $json_string = $json->encode(\%perl_data);
print ref(\$json_string) . "\n";
print $json_string . "\n";
The encode()
method of the $json
object takes a reference (denoted by the backslash) to the Perl data structure you want to encode ( %perl_data
).
Running this code in a command line interface should print the following lines:
SCALAR
{"ticket":{"comment":{"body":"The smoke is very colorful."}}}
The first line tells you the data is no longer a hash but a scalar. The second line displays the JSON.
To learn more about the encode()
method, see the JSON module documentation on CPAN.
To learn how to use Perl to make API requests containing JSON data, see the REST API tutorial for Perl .
Pretty printing the JSON
You can pretty print the JSON by setting ->pretty()
when creating the $json
instance. Example:
my $json = JSON->new->pretty();
The example should now print:
{
"ticket" : {
"comment" : {
"body" : "The smoke is very colorful."
}
}
}
Writing the JSON to a file
You can write the JSON to a new file named json.txt with the following lines:
open(FH, '>', "json.txt") or die "I couldn't open the file $!.\n";
print FH $json_string;
close FH;
See Using JSON in cURL requests to use JSON files in cURL requests.
Using JSON in cURL statements
You can use the JSON output produced in by the various methods in Converting data in your code to JSON above and paste it directly in cURL statements to update and create data in a Zendesk product. Example:
curl https://{subdomain}.zendesk.com/api/v2/tickets/{id}.json \
-d '{"ticket":{"comment":{"body":"The smoke is very colorful."}}}' \
-H "Content-Type: application/json" \
-v -u {email_address}:{password} \
-X PUT
The cURL statement includes the JSON data for adding a ticket comment (the -d flag stands for data ). To learn more about cURL, see Installing and using cURL . Windows users: See also Using cURL in Windows .
If the JSON data is too lengthy to fit comfortably in a cURL statement, you can move it to a file and then import the file in the cURL statement using the @filename
syntax. Here's how:
-
Create a file named json.txt (or something along those lines) and move the JSON to the file. Example:
{"ticket":{"comment":{"body":"The smoke is very colorful."}}}
Python and Perl will also let you write JSON directly to a file. See the instructions for Python and Perl above.
-
Change the cURL statement to import the JSON data with the
@filename
syntax:curl https://{subdomain}.zendesk.com/api/v2/tickets/{id}.json \ -d @json.txt \ -H "Content-Type: application/json" \ -v -u {email_address}:{password} \ -X PUT
Note : In Windows, replace the line-ending backslash characters with caret (^) characters.
-
Before running the statement, use the cd command (for change directory) to navigate to the folder that contains the file. Example:
$ cd json_files
-
Run the cURL statement.
11 Comments
Nice article.
To convert JSON into readable date to be used in Excel I suggest downloading and install Microsoft Power Query Add-in, It's a really powerful tool that can read and convert JSON data straight into Excel.
Download link: https://www.microsoft.com/en-gb/download/details.aspx?id=39379
Any suggestions for importing the JSON. I was able to create the JSON to get the data (articles from sandbox), but it didn't pull any of the pictures. How do I get the pictures using curl to create the JSON.
I am am unable to load the JSON I created. (I do know the correct domain and credentials in the command)
curl https://mydomain.zendesk.com/api/v2/help_center/sections/360022690834/articles.json ^
-d '{"article": {"title": "Taking photos in low light", "body": "Use a tripod", "locale": "en-us" }, "notify_subscribers": false}' ^
-v -u stassa@mydomain.com:mypassword -X POST -H "Content-Type: application/json"
Hi Stassa. This article was more of an example on working with JSON rather than a solution to fully export and import production article data.
You would have to modify the code to pull down images using the Articles Attachment APIs, save those images somewhere, then use the Create Article Attachment API.
This "Backing up your knowledge base with the Zendesk API" is also an article and example (i.e. for demonstration purposes) of pulling article data. It might have some additional useful info.
This comment on the above article, in particular, speaks to an idea on handling attachments:
https://develop.zendesk.com/hc/en-us/articles/360001074288-Backing-up-your-knowledge-base-with-the-Zendesk-API?page=2#comment_360000439047
Hope there are some ideas here that help get you to your next step.
Thank you, much appreciated,
We are trying to use API to bring in tickets from a partner system. The lack of line breaks makes the ticket description almost unusable. Is there a way to make the JSON pretty in Zendesk?
EDIT: I found that we can use "html_body" in place of "body" to send formatted comment text through the API
Yes, that's the best course. Thanks for posting that follow-up Allison.
I can send a perfectly formatted JSON from a python script, receive an HTML 201 response status but the JSON data is not processed. When I change the JSON by force to use double-quotes rather than single-quotes and issue the same API call, I get the desired result.
There seems to be an absolute insistence by the API to use double-quotes in JSON rather than the default single-quotes. Can you confirm this? Thanks in advance.
Hi Jonah,
Double quotes are required in JSON for strings. From json.org: "A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. "
Charles
Thank you, Charles.
Thank you for your prompt reply. I had a fun time taking an existing Python dictionary (which defaults to single-quotes in Python) and manipulating it sufficiently so that ZD API would ingest it successfully and not treat it as a null payload.
Best, Regards
Jonah
Hi Jonah,
The easiest way is to use the Python JSON library to convert Python dictionaries to JSON objects before sending them off in your API requests. See https://docs.python.org/3.7/library/json.html. Example:
Please sign in to leave a comment.