[SalesForce] LWC – Extracting data from a JSON Object

I trying to extract the values from a JSON object.
This is the code to console log the retrieved record data –

console.log(JSON.stringify(data));

And here is the output in the JSON viewer

enter image description here

And this is the code I wrote to extract just the value of the Segment_ID__c field

console.log(JSON.stringify(data.fields.Segment_ID__c.value));

Below is the snip of the error I get when I load the record page

enter image description here

Reference for Matthew Souther

Matthew here is full code –

import { LightningElement, api, wire, track } from 'lwc';
import { getRecord, getFieldValue  } from 'lightning/uiRecordApi';
import loadPersonalizedOffers from "@salesforce/apex/PersonalizedOffersController.loadPersonalizedOffers";

let FIELDS = ['Account.Segment_ID__c'];

export default class Personalized_offers extends LightningElement {
    @api recordId;
    @api objectApiName;
    @track segment;
    
    @wire(getRecord, {
        recordId: '$recordId',
        fields: FIELDS
      }) segmentId( data, error ) {
          if(data) {
            //console.log(JSON.stringify(data));
            console.log(JSON.stringify(data.fields.Segment_ID__c.value));
          }
          else if(error) {
           
          }
      };
} 

EDIT – Raw Output

  1. console.log(JSON.stringify(data));
    {"data":{"apiName":"Account","childRelationships":{},"id":"0011700001IAt7EAAT","lastModifiedById":"00517000007IbsaAAC","lastModifiedDate":"2021-02-06T18:26:54.000Z","recordTypeId":"01241000001AMf6AAG","recordTypeInfo":{"available":true,"defaultRecordTypeMapping":false,"master":false,"name":"Customer","recordTypeId":"01241000001AMf6AAG"},"systemModstamp":"2021-02-06T18:26:54.000Z","fields":{"Segment_ID__c":{"displayValue":null,"value":"a2n17000000EhO7AAK"}}}}

  2. console.log(JSON.Stringify(data.fields));
    enter image description here

Best Answer

The error you're receiving is telling you that data.fields is undefined.

Looking at your code, you have segmentId( data, error ) { which is essentially declaring two objects to be passed into your function.

As per the docs (https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.data_wire_service_about), you need a single object with a data and error property.

Therefore you need to replace segmentId( data, error ) { with segmentId( { data, error } ) {

Related Topic