Home  >  Article  >  Web Front-end  >  Summary of methods for judging json in javascript_javascript skills

Summary of methods for judging json in javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:42:131169browse

Simply put, JSON can convert a set of data represented in a JavaScript object into a string (pseudo-object), which can then be easily passed between functions or used in asynchronous applications. Passed from the Web client to the server-side program. This string looks a little weird (you'll see a few examples later), but JavaScript interprets it easily, and JSON can represent more complex structures than name/value pairs. For example, arrays and complex objects can be represented rather than just simple lists of keys and values.

Check whether json is empty

Copy code The code is as follows:

var jsonStr ={};

1. Determine whether json is empty

Copy code The code is as follows:

jQuery.isEmptyObject();

2. Determine whether the object is empty:

Copy code The code is as follows:

if (typeOf(x) == "undefined")
if (typeOf(x) != "object")
if(!x)

The third method is the simplest method, but the third method cannot be judged by the mutually exclusive method if (x). It can only be added in front of the object!

3. The json key cannot be repeated;

Copy code The code is as follows:

jsonStr[key]="xxx"

If it exists, it will be replaced, if it does not exist, it will be added.

4. Traverse json

for(var key in jsonStr){

  alert(key+" "+jsonStr[key])

}
isJson = function(obj){
  var isjson = typeof(obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
  return isjson;
}
if (!isJson(data)) data = eval('('+data+')');//将字符串转换成json格式

Structures in JSON: objects and arrays.

1. Object

An object starts with "{" and ends with "}". Each "key" is followed by a ":", and "'key/value' pairs" are separated by ",".

Copy code The code is as follows:

packJson = {"name":"nikita", "password":"1111"}

2. Array

Copy code The code is as follows:

packJson = [{"name":"nikita", "password":"1111"}, {"name":"tony", "password":"2222"}];

An array is an ordered collection of values. An array starts with "[" and ends with "]". Use "," to separate values.

The above is the article introducing the judgment method of json in js. I hope you like it.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn