Reputation: 13120
Here's 2 javascript variables:
<script language="javascript" type="text/javascript">
var example1 = 'Mr.:1|Mrs.:2|Ms.:3|Dr.:4|Sr.:5|Jr.:6';
var example2 = {'Mr.':'1','Mrs.':'2','Ms.':'3','Dr.':'4','Sr.':'5','Jr.':'6'}
</script>
With javascript, is there a way to detect which one is not json
?
Upvotes: 0
Views: 96
Reputation: 3778
Use try catch and handle accordingly:
function IsJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
Upvotes: 2
Reputation: 85518
like this
try {
JSON.parse(example1);
} catch (e) {
console.log(example1+' is not valid JSON');
}
Upvotes: 1
Reputation: 5640
if you want to get the type of the variable in js,
You can try this
typeof("somevalue")
//returns string
typeof array or object will return you 'object' like
var arr = [];
typeof(arr) // returns 'object'
Upvotes: 1
Reputation:
You can use the JSON.parse function: http://msdn.microsoft.com/en-us/library/cc836466%28v=vs.85%29.aspx
This will throw an exception if the text passed into it is not valid JSON.
Edit:
The comments noting that you have not pasted JSON code are correct. This code:
var json = {"var1":"val1"};
Is actually a JavaScript Object. It looks remarkably similar, and it's quite easy to go between the two (using JSON.stringify and JSON.parse) but they are different concepts.
Upvotes: 5