简体   繁体   English

JSON-验证Json数组或对象

[英]JSON - Validating a Json array or Object

Here's 2 javascript variables: 这是2个JavaScript变量:

<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 ? 使用javascript,有没有一种方法可以检测哪个不是json

You can use the JSON.parse function: http://msdn.microsoft.com/en-us/library/cc836466%28v=vs.85%29.aspx 您可以使用JSON.parse函数: http : //msdn.microsoft.com/zh-cn/library/cc836466%28v=vs.85%29.aspx

This will throw an exception if the text passed into it is not valid JSON. 如果传递给它的文本不是有效的JSON,则将引发异常。

Edit: 编辑:

The comments noting that you have not pasted JSON code are correct. 指出您尚未粘贴JSON代码的注释是正确的。 This code: 这段代码:

var json = {"var1":"val1"};

Is actually a JavaScript Object. 实际上是一个JavaScript对象。 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. 它看起来非常相似,并且在两者之间使用JSON.stringify和JSON.parse很容易,但是它们是不同的概念。

Use try catch and handle accordingly: 使用try catch并相应地处理:

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

if you want to get the type of the variable in js, 如果要获取js中变量的类型,

You can try this 你可以试试这个

typeof("somevalue")
//returns string

typeof array or object will return you 'object' like typeof数组或对象将返回“对象”,例如

var arr = [];
typeof(arr) // returns 'object'

like this 像这样

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM