Salesforce, a customer relationship management (CRM) platform with comprehensive data management tools and reporting capabilities, provides robust solutions for businesses. In this tutorial, we will walk you through how to get grouped JSON Data from Salesforce Reports by creating a simple report in Salesforce data and generate JSON output with group by.
This step-by-step guide will show you how to convert your Salesforce data into structured JSON formats for easier integration and analysis — perfect for anyone in Salesforce: administrators, developers, or data visualization specialists.
How to Get JSON Data from Salesforce Reports?
Writing JSON outputs from Salesforce data helps integrate easily into other applications for better enhancement, data visualization, and reporting.
The following aspect is a good point of interest for clustering the data fields as it provides a better perspective to organize the information required for analyzing trends and patterns. In this quick Salesforce tutorial, we cover everything from establishing API access through sending queries, all the way to extracting grouped JSON data.
Prerequisites
Make sure you have the following before you start:
- Salesforce Account: Access to a Salesforce org with the right set of permissions.
- API Access: Ensure your Salesforce edition allows access through the API (Enterprise, Unlimited, Developer, or Performance editions).
- Developer Tools: Familiarity with tools such as Salesforce Workbench, Postman, or an IDE for Apex coding.
- Fundamentals of SOQL: Understanding Salesforce Object Query Language (SOQL) used to query and search data.
Salesforce Reports and SOQL
There are two main ways of querying data in Salesforce:
- Reports: A no-code reporting interface. Nevertheless, there are some restrictions such as you cannot export grouped data directly from reports in JSON format.
- SOQL (Salesforce Object Query Language): A robust query language that allows highly accurate data retrieval, enables grouping and aggregation of records, and supports JSON output via APIs.
SOQL, along with Salesforce APIs, is the recommended path for advanced data manipulation and JSON generation.
Using SOQL to Group Data
SOQL supports GROUP BY
clauses, which let you aggregate data on specific fields. This is essential for organizing the data before converting it into JSON format. Below is an example of a SOQL query that groups opportunities by StageName
:
SELECT StageName, COUNT(Id)
FROM Opportunity
GROUP BY StageName
This query fetches the count of opportunities for each stage, which can then be turned into JSON.
How to Get JSON Response Using Salesforce APIs
Salesforce APIs, like the REST API, allow you to run SOQL queries and get the results back in JSON format. These APIs enable you to automate the extraction of data and easily connect Salesforce data with other systems.
Step-by-Step Tutorial
Salesforce API Access Step 1 — Set Up
- Create a Connected App:
- Go to Setup > App Manager and click New Connected App.
- Enter the mandatory information like Connected App Name, API Name, and Contact Email.
- Enable OAuth Settings:
- Check Enable OAuth Settings.
- Specify the Callback URL (e.g.,
https://localhost
for testing). - Choose relevant OAuth Scopes (e.g., Full Access).
- Generate Security Token:
- Navigate to Settings > My Personal Information > Reset My Security Token.
- Click Reset Security Token to receive it via email.
Step 2: Build Your SOQL Query
Choose the data you want to group and aggregate. For example, to count contacts and group them by AccountId
:
SELECT AccountId, COUNT(Id)
FROM Contact
GROUP BY AccountId
Step 3: Run the Query and Get JSON
Using Salesforce Workbench
- Login to Workbench:
- Visit Salesforce Workbench.
- Sign in with your Salesforce account.
- Navigate to SOQL Query:
- Go to Queries > SOQL Query.
- Enter Your Query:
- Input your SOQL query in the query box.
- Select Response Format:
- Select JSON as the response type.
- Execute the Query:
- Press the Execute button to retrieve the grouped JSON data.
Example Output
{
"totalSize": 3,
"done": true,
"records": [
{
"attributes": {
"type": "AggregateResult"
},
"AccountId": "001xx000003DGbYAAW",
"expr0": 15
},
{
"attributes": {
"type": "AggregateResult"
},
"AccountId": "001xx000003DGbZAAW",
"expr0": 10
},
{
"attributes": {
"type": "AggregateResult"
},
"AccountId": "001xx000003DGbXAAW",
"expr0": 20
}
]
}
Step 4: Using the Received JSON Data
With the JSON output in hand, you can now parse it using JavaScript and Python or connect it to applications (e.g., Slackbot) for further processing.
Example in JavaScript
const jsonData = {
"totalSize": 3,
"done": true,
"records": [
{
"attributes": { "type": "AggregateResult" },
"AccountId": "001xx000003DGbYAAW",
"expr0": 15
},
// Additional records...
]
};
// Parsing the JSON data
jsonData.records.forEach(record => {
console.log(`Account ID: ${record.AccountId}, Contact Count: ${record.expr0}`);
});
Tools for Easy Extraction of Data
Using Salesforce Workbench
Salesforce Workbench is a powerful, web-based tool for interacting with Salesforce APIs without writing code. It allows you to execute SOQL queries and retrieve data in various formats, including JSON.
Advantages:
- User-friendly interface.
- No coding required.
- Supports various Salesforce APIs.
Steps:
- Log in to Workbench.
- Navigate to Queries > SOQL Query.
- Enter and execute your query.
- Select JSON as the format of output.
Making API Requests with Postman
Postman is a versatile tool for making API requests, which is useful for automating data retrieval and integrating Salesforce data with other systems seamlessly.
Advantages:
- Supports automation and scripting.
- Easy to manage multiple API requests.
- Useful for testing and debugging.
Steps:
- Authenticate with Salesforce:
- Use OAuth 2.0 to obtain an access token.
- Create a GET Request:
- Endpoint:
https://yourInstance.salesforce.com/services/data/vXX.X/query?q=YOUR_SOQL_QUERY
- Endpoint:
- Set Headers:
Authorization: Bearer YOUR_ACCESS_TOKEN
Content-Type: application/json
- Send the Request:
- Execute the request to retrieve JSON data.
Apex Code for Creating Custom JSON Outputs
For more advanced use cases, you can write Apex classes to execute SOQL queries and format the output as JSON.
Example Apex Class
public with sharing class GroupedDataController {
@AuraEnabled(cacheable=true)
public static String getContactsGrouped() {
// Example: Grouping contacts by AccountId
List<AggregateResult> groupedResults = [SELECT AccountId, COUNT(Id) cnt FROM Contact GROUP BY AccountId];
List<Map<String, Object>> results = new List<Map<String, Object>>();
for(AggregateResult ar : groupedResults){
Map<String, Object> record = new Map<String, Object>();
record.put('AccountId', ar.get('AccountId'));
record.put('ContactCount', ar.get('cnt'));
results.add(record);
}
return JSON.serialize(results);
}
}
Usage:
- Deploy the Apex class to your Salesforce org.
- Call the
getContactsGrouped
method via Lightning Components, Visualforce pages, or external applications.
Best Practices
- Optimize SOQL Queries:
- Use selective filters to minimize data retrieval.
- Avoid unnecessary fields to reduce payload size.
- Handle Large Data Sets:
- Implement pagination for queries returning extensive data.
- Use batch processing for large-scale data operations.
- Secure API Access:
- Use OAuth 2.0 for secure authentication.
- Limit API access permissions to necessary scopes only.
- Error Handling:
- Implement robust error handling in your applications to manage API failures gracefully.
- Data Privacy Compliance:
- Ensure compliance with data protection regulations (e.g., GDPR) when handling sensitive data.
Conclusion
Salesforce data reports can be formatted as grouped JSON outputs, which improve integration and analytical capabilities with other systems — helping organizations leverage their investments in the CRM more effectively. It allows you to easily extract data in JSON format through SOQL queries and Salesforce APIs. Salesforce offers flexibility by using tools like Workbench and Postman or writing custom Apex code to obtain the data required for your reports.
Start converting Salesforce Reports to JSON output now for powerful data strategies!