I have a requirement where in I get JSON data from backend and I have to show that in textarea.currently, the data comes but its not formatted and validated.Now
1)How can I beautify JSON in the textarea ?
2)How can I validate it before saving ?
I have searched for all javascript/jquery plugins but I am not getting what I want.I want something like jslint
Thanks in advance
Use JSON.stringify(object, 0, 4) with space parameter for a formatted JSON string.
var object = [{ "stop_id": 70021, "stop_name": "CALTRAIN - 22ND ST STATION", "stop_lat": 37.757692, "stop_lon": -122.392318, "zone_id": 3329 }, { "stop_id": 70022, "stop_name": "CALTRAIN - 22ND ST STATION", "stop_lat": 37.757692, "stop_lon": -122.392318, "zone_id": 3329 }, { "stop_id": 70151, "stop_name": "CALTRAIN - ATHERTON STATION", "stop_lat": 37.464458, "stop_lon": -122.198152, "zone_id": 3331 }];
document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
You can use the following to check that a string is a valid representation of a JSON object:
function parseJson(str) {
try {
return JSON.parse(str);
}
catch (err) {
return false;
}
}
Usage:
var parsed = parseJson(someInput);
if (parsed === false) {
// Invalid json
}
If you also need to validate the object using some custom logic (e.g. "I need your object to have attributes X and Y"), take a look at JsonSchema.
Related
I have the following data which is being parsed and then I am looping through to attempt to get each state ID and name.
{
"billing": {
"ACT": "Australian Capital Territory",
"NSW": "New South Wales",
"NT": "Northern Territory",
"QLD": "Queensland",
"SA": "South Australia",
"TAS": "Tasmania",
"VIC": "Victoria",
"WA": "Western Australia"
},
"shipping": {
"ACT": "Australian Capital Territory",
"NSW": "New South Wales",
"NT": "Northern Territory",
"QLD": "Queensland",
"SA": "South Australia",
"TAS": "Tasmania",
"VIC": "Victoria",
"WA": "Western Australia"
}
}
data = '{"billing":{"ACT":"Australian Capital Territory","NSW":"New South Wales","NT":"Northern Territory","QLD":"Queensland","SA":"South Australia","TAS":"Tasmania","VIC":"Victoria","WA":"Western Australia"},"shipping":{"ACT":"Australian Capital Territory","NSW":"New South Wales","NT":"Northern Territory","QLD":"Queensland","SA":"South Australia","TAS":"Tasmania","VIC":"Victoria","WA":"Western Australia"}}';
data = jQuery.parseJSON( data );
billingData = data.billing;
$(billingData).each( function( key, value ) {
console.log( key + value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I am expecting the console to loop through each state ID and the label, but I get they key as 0 and the value as an object, I have also tried looping through the outputted object (contained in value from the original .each).
I have also tried looping through billingData[0].
You need to use jQuery.each() instead of .each() to do this work.
The .each() loop through jquery elements but jQuery.each() loop through array or object.
data = '{"billing":{"ACT":"Australian Capital Territory","NSW":"New South Wales","NT":"Northern Territory","QLD":"Queensland","SA":"South Australia","TAS":"Tasmania","VIC":"Victoria","WA":"Western Australia"},"shipping":{"ACT":"Australian Capital Territory","NSW":"New South Wales","NT":"Northern Territory","QLD":"Queensland","SA":"South Australia","TAS":"Tasmania","VIC":"Victoria","WA":"Western Australia"}}';
data = jQuery.parseJSON(data);
billingData = data.billing;
$.each(billingData, function(key, value) {
console.log(key +": "+ value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
billingData is not an array. It's an object. jQuery each will let you iterate through an object as though it were an array, or you could just use object methods:
data = '{"billing":{"ACT":"Australian Capital Territory","NSW":"New South Wales","NT":"Northern Territory","QLD":"Queensland","SA":"South Australia","TAS":"Tasmania","VIC":"Victoria","WA":"Western Australia"},"shipping":{"ACT":"Australian Capital Territory","NSW":"New South Wales","NT":"Northern Territory","QLD":"Queensland","SA":"South Australia","TAS":"Tasmania","VIC":"Victoria","WA":"Western Australia"}}';
data = jQuery.parseJSON(data);
billingData = data.billing;
Object.keys(billingData).forEach(function(key) {
console.log(key + ": " + billingData[key])
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
There are two types of each:
$.each(array, function( key, value ) {
});
$('.element').each(function () {
});
When importing data from a file this is one of the results:
{
id: 1234,
name: "Store name",
street: "Street",
house_number: "19",
postal_code: "12346",
city: "Brussel",
country: "NL",
formatted_opening_times: {2=>[09:00 - 22:00] 4=>[09:00 - 22:00] 6=>[10:00 - 18:00] 1=>[09:00 - 22:00] 5=>[09:00 - 20:00] 3=>[09:00 - 22:00] 0=>[09:00 - 22:00]},
open_now: true
}
We are able to show the data, but have difficulty with the formatted_opening_times. We would like to show it like:
Monday: 09:00 - 02:00
Tuesday: 09:00 - 22:00
...
I have tried to parse the data in JSON and show the content:
var opening_times = JSON.parse(storeSpecs.data.formatted_opening_times);
var content = "Monday: "
content += ${opening_times[0][2]}
But result in error console is saying
Uncaught SyntaxError: Unexpected number in JSON at position 1
Hope someone can help.
That is not JSON. A hack would be to replace the "=>" with ":" and the "[" or "]" with quotes.
var org = "{2=>[09:00 - 22:00] 4=>[09:00 - 22:00] 6=>[10:00 - 18:00] 1=>[09:00 - 22:00] 5=>[09:00 - 20:00] 3=>[09:00 - 22:00] 0=>[09:00 - 22:00]}"
var jsonStr = org.replace(/([0-9]+)=>/g, '"$1":')
.replace(/\[/g,'"')
.replace(/\]/g, '",')
.replace(/,\}$/, '}')
var res = JSON.parse(jsonStr);
I found a script that's used to extract saved articles from Feedly (by running it inside Chrome's Inspect Element console), but I'd like to tweak it a bit for my needs. I'm not a developer or anything like that so I'd appreciate it if someone could help!
Here's part of the script:
json = ""
function copyToClipboard() {
// Loop through the DOM, grabbing the information from each bookmark
map = jQuery("#section0_column0 div.u0Entry.quicklisted").map(function(i, el) {
var $el = jQuery(el);
var regex = /published:(.*)\ --/i;
return {
title: $el.data("title"),
url: $el.data("alternate-link"),
time: regex.exec($el.find("div.lastModified span").attr("title"))[1]
};
}).get(); // Convert jQuery object into an array
// Convert to a nicely indented JSON string
json = JSON.stringify(map, undefined, 2)
Here's an example of what it returns:
[
{
"title": "Blog post headline",
"url": "http://urlofblogpost.com/article",
"time": "Tue, 10 Dec 2014 21:00:00 GMT"
},
{
"title": "Blog post2 headline",
"url": "http://urlofblogpost.com/article2",
"time": "Tue, 10 Dec 2014 21:00:00 GMT"
},
]
Here's what I'd like it to return:
Blog post headline
Blog post2 headline
The most I could do on my own was delete the "time" part from the script, remove the brackets, and isolate the titles and URLs (using a text editor):
Blog post headline
http://urlofblogpost.com/article
Is there any way to change the script to get it in links?
Just Iterate through the json:
Javascript:
function copyToClipboard() {
// Loop through the DOM, grabbing the information from each bookmark
map = jQuery("#section0_column0 div.u0Entry.quicklisted").map(function(i, el) {
var $el = jQuery(el);
var regex = /published:(.*)\ --/i;
return {
title: $el.data("title"),
url: $el.data("alternate-link"),
time: regex.exec($el.find("div.lastModified span").attr("title"))[1]
};
}).get(); // Convert jQuery object into an array
var theLink = '';
$.each(yourJson, function(k,v){
theLink += "<a href=" + v.url + " >" + v.title + " </a>, \n";
});
window.prompt('my link', theLink);
I create js fiddle for you play: http://jsfiddle.net/reptildarat/GG5BP/4/
What goes wrong if 77>602? I tried in IE, Firefox and Chrome
function getMaxValue(data){
var maxValue=0;
for(var i=0;i<data.length;i++){
if(data[i].value>maxValue){
console.log(data[i].value +">"+maxValue);
maxValue=data[i].value;
}
}
console.log("MaxValue:"+maxValue);
return maxValue;
}
I get my data from a json:
[{
"keyword": "User: Allen-P",
"value": "602"
}, {
"keyword": "From: phillip.allen#enron.com",
"value": "598"
},
{
"keyword": "Date: 2001",
"value": "276"
},
{
"keyword": "Subject: Re:",
"value": "228"
},
{
"keyword": "Date: 2001 Apr",
"value": "77"
},
]
Needed to add some useless description for StackOverflow. Please help me;). The json file is a bit bigger and just an example.
Strings are compared alphabetically even if they contain numbers. The character '7' comes after the character '6', alphabetically, so indeed, in terms of strings, "77" > "602".
The solution is to convert them to numbers first:
if(parseFloat(data[i].value) > maxValue){
Or for sake of brevity, the unary + operator will also do this:
if(+data[i].value > maxValue){
You're currently comparing an integer with a string, which doesn't reliably work in this situation.
Either change your JSON and unquote the values, or use the following code instead:
function getMaxValue(data){
var maxValue=0;
for(var i=0;i<data.length;i++){
if(parseInt(data[i].value) > maxValue) {
console.log(data[i].value +">"+maxValue);
maxValue=data[i].value;
}
}
console.log("MaxValue:"+maxValue);
return maxValue;
}
Also read this for reference.
You need to use parseInt(value,10) to convert the value from a string to a number
I have a JSON format result sent back to the client that hold the $quot sign. for some unknown reason the code breaks.
Here is the code that bricks from ext-all-debug:
doDecode = function(json){
return eval("(" + json + ")"); FAILS HERE
},
Here is my JSON as it left the server (As far as I know , I hope the server doesn't take the time to decode this " on its free time.):
{
success: true,
total: 1,
results: [{
"ID": -1,
"Value": "POChangeRequestlblCustomerCatalogNumber",
"Description": "",
"Labels": {
"1": {
"ID": -1,
"LanguageID": 1,
"Value": "Catalog Number",
"ToolTip": "",
"LanguageName": "English",
"KeyID": -1,
"KeyValue": "POChangeRequestlblCustomerCatalogNumber",
"KeyDescription": ""
},
"2": {
"ID": -1,
"LanguageID": 2,
"Value": """, <<< THIS IS THE BAD PART!!!
"ToolTip": "",
"LanguageName": "Hebrew",
"KeyID": -1,
"KeyValue": "POChangeRequestlblCustomerCatalogNumber",
"KeyDescription": ""
}
},
"ServerComments": "1"
}]
}
this JSON is sent in a text/html content type as it is the result of a file upload operation. could that be part of the problem?
Ok, I have continued to trace down the problem and found that ExtJS does this function on the returned value from a hidden iframe:
doFormUpload : function(o, ps, url){
...
try{
doc = frame.contentWindow.document || frame.contentDocument || WINDOW.frames[id].document;
if(doc){
if(doc.body){
if(/textarea/i.test((firstChild = doc.body.firstChild || {}).tagName)){
r.responseText = firstChild.value;
}else{
r.responseText = doc.body.innerHTML; << THIS IS WHERE MY " get decoded back to " (sign)
}
}
r.responseXML = doc.XMLDocument || doc;
}
}
catch(e) {}
...
}
Is there a good workaround for this issue. it seems that the browser automatically decodes the value???? any one???? this is a major issue !!
Here is how I worked around it.
The problem was that all browsers automatically decode the & quot; signs.
So I have fixed the Ext doFormUpload function to look like this:
doFormUpload : function(o, ps, url){
...
try{
doc = frame.contentWindow.document || frame.contentDocument || WINDOW.frames[id].document;
if(doc){
if(doc.body){
if(doc.body.innerText){
r.responseText = doc.body.innerText;
}else{
r.responseText = doc.body.innerHTML.replace(/<pre>/ig,'').replace(/<\/pre>/ig,'');
}
}
r.responseXML = doc.XMLDocument || doc;
}
}
catch(e) {}
...
}
In addition from now on the content type that the server is returning is "text/plain"
this prevents the browsers from decoding the data.
I also added a little workaround from FF that does not support innerText property but adds the tag that wraps the response.
This is an ugly hack to the ExJS framwork but it worked for me.
Hopefully someone will notice the question and have some better idea on how to solve it.
It doesn't look like the encoded quote is causing your issue -- take a look at this jsfiddle to see that the Ext.decode function works perfectly fine when decoding a JSON string containing ":
http://jsfiddle.net/MXVvR/
Are you sure that the server is returning a JSON string and not a JSON object? Inspect the server response using Firebug, Fiddler, or Chrome Developer Tools to see exactly what's coming back from the server.