I have JSON text in excel cells but it’s hard to read. I want to format the text so it’s easier to read the variable/value.
var ss = SpreadsheetApp.getActive();
var jVal = ss.getRange('N145').getValue();
var jFormat = JSON.stringify(jVal,null, 3);
SpreadsheetApp.getUi().alert(jFormat);
Text in Google Sheet:
{payload:{client:"something",messages:[{name:"something",contentType:"something",messageType:"something",content:"something",liveChatGroupType:"",chatCondition:"something",liveChatGroup:"something"}],version:"2.0",params:{type:"dtree"}},messageType:"PAYLOAD"}
I am getting output as:
"{payload:{client:"something",messages:[{name:"something",contentType:"something",messageType:"something",content:"something",liveChatGroupType:"",chatCondition:"something",liveChatGroup:"something"}],version:"2.0",params:{type:"dtree"}},messageType:"PAYLOAD"}"
I want to look like:
{
"payload":{
"client":"something",
"messages":[
{
"name":"something",
"contentType":"something",
"messageType":"something",
"content":"something",
"liveChatGroupType":"",
"chatCondition":"something",
"liveChatGroup":"something"
}
],
"version":"2.0",
"params":{
"type":"dtree"
}
},
"messageType":"PAYLOAD"
}
2
Answers
Suggestion: Check the JSON Format and then use JSON.parse within JSON.stringify
In terms of the format, you need to edit the JSON in the specified cell by making the keys into string since the getValue() function only reads
values of type Number, Boolean, Date, or String
. Thus, JSON objects will be automatically read as string values (which resulted in the output from your post).As a workaround, you may change:
to:
Afterwards, you may use the modified script below to display the json in the alert popup:
In the script above, the string read by the getValue() is first converted into a JSON object using
JSON.parse
and is then converted back into a formatted string for display usingJSON.stringify
.The console output should look like this:
While the alert popup should look like this:
References:
The data is not complying JSON. The main problem is that double quotes have been stripped from many elements. As @PatrickdC points out the data has to be converted to complying JSON.
Let’s assume that you output is in Cell B1.
=REGEXREPLACE(B1,"[{]","{""")
=REGEXREPLACE(B2,"[:]",""":")
=REGEXREPLACE(B3,"[,]",",""")
SAMPLE
PRINT BEAUTIFIED JSON
Refer Indent pretty JSON in Google Sheet Apps Script