How to Retrieve and Operate on JSON in LWC?

How to Retrieve and Operate on JSON in LWC?

On April 30, 2025, Posted by , In LWC Essentials, With Comments Off on How to Retrieve and Operate on JSON in LWC?

In Salesforce, when working with JSON data stored in a custom object’s field, it’s important to correctly retrieve and parse that data in a Lightning Web Component (LWC). This content will provide more insights into how to handle this scenario, considering different approaches and use cases.

Retrieving a JSON Field Using the getRecord Wire Adapter

If your LWC knows the record ID in advance and you are working with a single record, you can easily retrieve the JSON field using the getRecord wire adapter. Here’s an example of how you can achieve this:

// JSONFieldLWC.js
import { LightningElement, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';

const FIELDS = ['CustomObj.sample_field'];

export default class JSONFieldLWC extends LightningElement {
    recordId = 'your-record-id';  // The record ID you want to fetch
    jsonData;

    @wire(getRecord, { recordId: '$recordId', fields: FIELDS })
    record({ error, data }) {
        if (data) {
            // Parse the JSON field from the record
            this.jsonData = JSON.parse(data.fields.sample_field.value);
            console.log('Parsed JSON:', this.jsonData);
        } else if (error) {
            console.error('Error retrieving record:', error);
        }
    }

    // Function to perform operations on the JSON data
    performOperations() {
        if (this.jsonData) {
            const value = this.jsonData.key;  // Access key-value pair from the JSON
            console.log('Value from JSON:', value);
        }
    }
}

Explanation:

  • The getRecord wire adapter retrieves the sample_field value, which contains the JSON string.
  • Once the data is received, we parse the JSON string using JSON.parse().
  • You can then access specific keys inside the JSON and perform operations as required.

CRS Info Solutions provides expert Salesforce training in Delhi, emphasizing hands-on experience and real-world scenarios. Sign up today for a free demo and begin your Salesforce learning adventure!

Handling Complex Queries with Apex Method

If you need to query records with a more complex WHERE clause or need to join multiple objects, using an Apex method is the better choice. Here’s an example of an Apex method to fetch records and return the JSON field:

// CustomObjController.cls
public with sharing class CustomObjController {
    @AuraEnabled(cacheable=true)
    public static String getSampleField(String recordId) {
        CustomObj obj = [SELECT sample_field FROM CustomObj WHERE Id = :recordId LIMIT 1];
        return obj.sample_field;  // Return the JSON string stored in the field
    }
}
// JSONFieldApexLWC.js
import { LightningElement, wire } from 'lwc';
import getSampleField from '@salesforce/apex/CustomObjController.getSampleField';

export default class JSONFieldApexLWC extends LightningElement {
    recordId = 'your-record-id';  // The record ID you want to fetch
    jsonData;

    @wire(getSampleField, { recordId: '$recordId' })
    handleResult({ error, data }) {
        if (data) {
            // Parse the JSON field returned by Apex
            this.jsonData = JSON.parse(data);
            console.log('Parsed JSON:', this.jsonData);
        } else if (error) {
            console.error('Error retrieving field data:', error);
        }
    }

    // Function to perform operations on the JSON data
    performOperations() {
        if (this.jsonData) {
            const value = this.jsonData.key;  // Access key-value pair from the JSON
            console.log('Value from JSON:', value);
        }
    }
}

Explanation:

  • This example demonstrates how to retrieve the sample_field JSON from Apex using a custom method.
  • The JSON string is returned from the Apex method and parsed in the LWC.
  • The performOperations() function accesses the parsed data and works with it.

See also: Sales Process and Forecasting in Salesforce

Refreshing Data After Scheduled Job Updates

When the field is updated by a scheduled job, the LDS cache does not automatically invalidate. To address this issue, you can use a Platform Event and EmpApi to notify the LWC when the data has been updated. Here’s how you can handle this:

Step 1: Define a Platform Event.

// SampleFieldUpdateEvent.evt
event SampleFieldUpdateEvent {
    string recordId;
}

Step 2: Publish the Platform Event in the scheduled job.

// ScheduledJob.cls
public class SampleFieldUpdateJob implements Schedulable {
    public void execute(SchedulableContext context) {
        // Update the field in your custom object
        CustomObj obj = [SELECT Id, sample_field FROM CustomObj WHERE ... LIMIT 1];
        obj.sample_field = '{"key": "value"}'; // New JSON value
        update obj;

        // Publish the platform event after updating
        SampleFieldUpdateEvent event = new SampleFieldUpdateEvent(
            recordId = obj.Id
        );
        EventBus.publish(event);
    }
}

Step 3: Subscribe to the Platform Event in your LWC.

// JSONFieldLWC.js
import { LightningElement, wire } from 'lwc';
import { subscribe, MessageContext } from 'lightning/messageService';
import SAMPLE_FIELD_UPDATE_CHANNEL from '@salesforce/messageChannel/SampleFieldUpdateEvent__c';

export default class JSONFieldLWC extends LightningElement {
    recordId = 'your-record-id';
    jsonData;
    
    @wire(MessageContext)
    messageContext;

    connectedCallback() {
        this.subscribeToPlatformEvent();
    }

    subscribeToPlatformEvent() {
        this.subscription = subscribe(this.messageContext, SAMPLE_FIELD_UPDATE_CHANNEL, (message) => {
            if (message.recordId === this.recordId) {
                this.refreshData();
            }
        });
    }

    refreshData() {
        // Manually refresh the data using the wire adapter or Apex method
        console.log('Refreshing data due to platform event');
        // Re-fetch the record data here
    }
}

Explanation:

  • The scheduled job updates the JSON field and publishes a Platform Event.
  • The LWC subscribes to this event using the lightning/messageService (empApi).
  • Upon receiving the event, the LWC triggers a data refresh to ensure it reflects the updated field value.

See also: Salesforce Developer interview questions for 5 years experience

Conclusion

By utilizing the getRecord wire adapter for simpler cases where only a single record is involved, or using an Apex method for more complex queries, you can efficiently retrieve JSON data stored in Salesforce fields. Handling updates via scheduled jobs can be managed using Platform Events, which helps keep your LWC in sync with the latest data.

CRS Info Solutions presents an in-depth Salesforce course tailored for beginners, guiding you through each phase of the learning process. Their interactive Salesforce training in Delhi, emphasizes skill-building, real-world insights, and a thorough grasp of core concepts. The course includes daily notes, video tutorials, interview preparation, and scenario-driven learning to help you gain the confidence and expertise necessary for Salesforce certification and career growth.

Join CRS Info Solutions’ Salesforce training to receive expert mentorship and certification prep, enhancing your skills and boosting your career opportunities..!!

Comments are closed.