理解和学习javascript JSON对象的例子

160 阅读3分钟

JSON是javascript对象符号的缩写。在了解Javascript的JSON对象之前,我们先来看看JSON的基础知识。

JSON简介

  • JSON是一种基于文本的文件格式,用来在软件应用程序之间保存和传输数据。通常情况下,浏览器向服务器发送请求数据,并接收JSON格式的响应数据。
  • JSON简单易读,重量轻
  • JSON是独立于语言的。所有的编程语言都支持理解JSON符号。
  • 它只代表这种格式的数据,不支持方法和函数。
  • JSON数据样本中不允许有注释
 `[  
  {  
    "name": "Tom",  
    "id": "1",  
    "age": 25  
  },{  
    "name": "Ram",  
    "id": "2",  
    "age": 35  
  }  
]  
`
```**JSON Syntax**   
  
JSON object is similar to javascript syntax  
JSON object holds key and value pairs separated by a colon. Each object and both key and value pair is separated by a comma.  
JSON array is represented using brackets which holds a list of similar elements  
Keys only accepts Strings, numbers but not arrays or object arrays  
Values can be number,Arrays,String,Objects,boolean,null  
_Simple JSON example_  

var emp={ "name":"Tom" }

var emp=[{ "name":"John" }, { "name":"Ram" }]

  
 JSON data can be represented in the form of Strings as well as files. The file extension is json. And content types for this files is application/json.  

## JSON object in javascript

  

JSON object is used to manipulate JSON format based files and strings. we can do the convert to/from a string using this method. There are only two methods available in javascript

### JSON.parse() method

Take the input as a string and returns the object.

**Syntax** is JSON.parse(stringObject\[, reviver\])

Arguments- 

_stringObject_ is a string to parse as JSON

_reviver_ \- is called during transformation to manipulate key and values and return it.and the return value is the object 

**Examples**   
The below are valid strings for parsing into a javascript object  

var jsonString = '{"name": "John","id": "1","age": 25}'; var jsonObject = JSON.parse(jsonString); console.log(typeof jsonString);// returns string console.log(typeof jsonObject);// returns object console.log(jsonString);// returns {"name": "John","id": "1","age": 25} console.log(jsonObject);// returns Objectage: 25id: "1"name: "John"__proto__: Object console.log(jsonObject.name); // returns John // valid json parsing JSON.parse('{}'); // returns {} JSON.parse('"hello"'); // returns "hello" JSON.parse('null'); // returns null JSON.parse('false'); // returns false

var test = JSON.parse('{"name":"kiran"}', (key, value) =>{ return typeof value === 'string' ? value.toUpperCase() // return value in uppercase : value // return everything else unchanged } ); console.log('t', test); // returns json object like {"name":"KIRAN"}


**JSON parse SyntaxError Example**   
throws _Syntaxerror_ when unable to parse string format to JSON object.  
 **Uncaught SyntaxError: Unexpected token \] in JSON at position**   

```markup
JSON.parse('[4, 1, 9, ]');  
JSON.parse('{"key" : "value", }');  

检查JSON字符串格式的解决方案或修复方法,并修复它。如果需要的话,你也可以检查在线JSON格式验证工具来验证它。

JSON Stringify方法

stringify方法用于将JSON值序列化为JSON字符串。
语法是JSON.stringify(jsonvalue[, replacer[, space]])
参数- jsonvalue是转换为JSON字符串的值
replacer - 是一个从完整的JSON字符串中过滤/值的函数。键/值可以用这个函数省略。这是可选的。
spacer - 第三个参数可以是字符串或数字
而返回值是JSON字符串
当发现一个循环引用时,会抛出一个TypeError("循环对象值")异常。有效的JSON stringify例子

 `  
const arrayJson = ['kiran', 'john', 'frank'];  
const stringArrayJson = JSON.stringify(arrayJson);  
console.log(stringArrayJson); // return ["kiran","john","frank"]  
`

JSON stringify reviver和空格的例子

 `const employeeString = {  
  id: 1,  
  name: 'Kiran',  
  age: 35  
};  
function replacer(key, value) {  
  console.log(typeof value);  
  if (key === 'age') {  
    return undefined;  
  }  
  return value;  
}  
const empJsonString = JSON.stringify(employeeString, replacer);  
console.log(empJsonString) // returns {"id":1,"name":"Kiran"}  
  
const empJsonString1 = JSON.stringify(employeeString, null,'--');  
console.log(empJsonString1) // returns {--"id": 1,--"name": "Kiran",--"age": 35}  
`
```**JSON stringify TypeError error**   
we are going to use stringify for the circular reference use case where parent and child objects are referenced. Uncaught TypeError: Converting circular structure to JSON  

const parentObject = {'childObject':null}; parentObject.childObject = parentObject; JSON.stringify(parentObject);


## Difference between json and jsonp

JSON

JSONP

Plain JSON

JSON with padding, JSON data + function call

This works with transferring data from client and server from same domain

get the data from a server from the different domain

Content type is application/json

Content type is application/javascript

{ "name": "Tom" }

function({ "name": "Tom" })

Easy to use and consume it

Not simple to understand and use it

### How to read data from JSON file in javascript? 

Reading data from JSON file is similar to retrieve data from the Ajax API Call. we can achieve this using **XMLHttpRequest** or **ajax jquery call**  
Steps  
  

1.  Create XMLHttpRequest object
2.  Handles onreadystatechange event- this will be called whenever status changed 
3.  readyState state is 4 and status is 200, request successfully connected and a successful response is returned 
4.  parse data using JSON parse method
5.  onError event is used to handle the errors.
6.  open and send methods are used to connect to resource and send the request to the the server.

  

` getJSONFileData: function() {
// XMLHttpRequest读取json例子
const xmlRequest = new XMLHttpRequest();
xmlRequest.overrideMimeType("application/json");
let path = 'file://C:/myproject/tsconfig.json';
xmlRequest.open('GET', path, true);
xmlRequest.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
const files = JSON.parse(xmlRequest.response);
} else {
console.log('Readed an error while reading json from file') ;
}
};

xmlRequest.onerror = function() {  
  console.log('Error occured during XMLHttpRequest');  
};  
xmlRequest.send();  

}
`

// ajax read json example $.ajax({ url : 'file:///C:/myproject/tsconfig.json', dataType : 'json', method : 'GET', success : function(response){ data = JSON.parse(response); console.log(data); } });