0

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?

3
  • 3
    Neither of those are JSON. Please explain what you're actually looking for Commented Sep 30, 2013 at 18:58
  • Actually neither one of the examples are JSON. The JSON spec requires that properties and string values be wrapped in double quotes ("), therefore neither example above is JSON. For the full spec, see this page. Commented Sep 30, 2013 at 18:58
  • the first is a string, the second is an object, you can check on that if you wish Commented Sep 30, 2013 at 18:58

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Use try catch and handle accordingly:

function IsJsonString(str) {
  try {
      JSON.parse(str);
  } catch (e) {
      return false;
  }
  return true;
}

Comments

1

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'

1 Comment

While typeof will tell you the type of the value in a javascript variable, it does not tell you whether a string value is valid JSON or not.
1

like this

try {
    JSON.parse(example1);
} catch (e) {
    console.log(example1+' is not valid JSON');
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.