JSON To Code For SPFx Solutions

Introduction

 
SharePoint Framework web part often involves interaction with the SharePoint list, data within Office 365, or any external Rest API. Most of these can be configured to return a response in JSON format. Dealing with JSON data is very frequent with SPFx development.
 
In this article, we will explore how we can interact with the JSON data and make use of extensions or plug-ins in Visual Studio code to generate code from JSON.
 

JSON Response in SPFx

 
Below are a few examples of how data is being returned in JSON format in various scenarios.
 
SharePoint List Item Processing
 
The below code shows the JSON response being returned during SharePoint list item retrieval using REST API.
  1. this._spHttpClient.get(`${this._currentWebUrl}/_api/web/lists/getbytitle('${listName}')/items?$select=FileRef/FileRef&$filter=FSObjType eq 0`,  
  2.     SPHttpClient.configurations.v1,  
  3.     {  
  4.         headers: {  
  5.             'Accept''application/json;odata=nometadata',  
  6.             'odata-version'''  
  7.         }  
  8.     })  
  9.     .then((response: SPHttpClientResponse): Promise<{ value: ICarouselImage[] }> => {  
  10.         return response.json();  
  11.     })  
  12.     .then((response: { value: ICarouselImage[] }): void => {  
  13.         resolve(response.value);  
  14.     }, (error: any): void => {  
  15.         reject(error);  
  16.     });  
MS Graph Processing
 
The below code shows the JSON response being returned during the MS Graph operation.
  1. graphClient  
  2.   .api("users")  
  3.   .version("v1.0")  
  4.   .select("displayName,mail,userPrincipalName")  
  5.   .get((err, res) => {    
  6.   
  7.     if (err) {  
  8.       console.error(err);  
  9.       return;  
  10.     }  
  11.   
  12.     // Prepare the output array  
  13.     var users: Array<IUserItem> = new Array<IUserItem>();  
  14.   
  15.     // Map the JSON response to the output array  
  16.     res.value.map((item: any) => {  
  17.       users.push( {   
  18.         displayName: item.displayName,  
  19.         mail: item.mail,  
  20.         userPrincipalName: item.userPrincipalName,  
  21.       });  
  22.     });  
  23.   
  24.     // Update the component state accordingly to the result  
  25.     this.setState(  
  26.       {  
  27.         users: users,  
  28.       }  
  29.     );  
  30.   });  
Other Examples
 
Calling REST API or MS Azure function from SPFx returns the response in the JSON format.
 

Process JSON in SPFx Code

 
In SPFx solutions, we define an interface to represent the data returned from JSON and use it in our code. To define the interface, firstly we have to analyze the JSON data and its format. If the JSON response is complicated, creating the interface by hand to represent it is a difficult job. Also, the interface should be revised if there is a change in the returned JSON (e.g. addition of new field, removal of an existing field, rename of fields, reposition of fields, etc.)
 

Paste JSON as Code – VSO Extension

 
An extension “Paste JSON as Code” for Visual Studio Code is available in the marketplace for free to help convert JSON to any language.
 
This extension can prove handy to convert JSON to any language including TypeScript, Python, Go, Ruby, C#, Java, Swift, Rust, Kotlin, C++, Flow, Objective-C, JavaScript, Elm, and JSON Schema.
 
Follow the below steps to install the extension to VSO.
JSON To Code For SPFx Solutions
  • Click "Install".
  • VS Code will open.
JSON To Code For SPFx Solutions
  • Click "Install" to install the extension.
Follow the below steps to use the extension,
  • Create a new file in VSO by File > New File.
  • Paste JSON in the created file.
  • In the VSO, click View > Command Palette.
JSON To Code For SPFx Solutions
  • Select “Open quicktype for JSON”.
  • The corresponding TypeScript code will be generated.
JSON To Code For SPFx Solutions
  • As the JSON is modified in the left section, the corresponding code will be auto-generated in the right section.
Follow the below steps to generate code in other languages,
  • Copy the JSON code to clipboard (CTRL + C).
  • In the VSO, click View > Command Palette.
  • Select “Paste JSON as Code”.
JSON To Code For SPFx Solutions
  • Select the target language. 
JSON To Code For SPFx Solutions
  • The types will be generated from JSON in the selected language.

Summary

 
SPFx development involves dealing with JSON response, which needs to be mapped to the equivalent interface in TypeScript to deal with the returned JSON response. The VSO extension – “Paste JSON as Code” is a handy extension for every SharePoint developer to generate types from JSON, which saves a lot of manual efforts.