JavaScript 什么是JSON文本
JavaScript对象表示法(JSON)用于在互联网上传输或交换信息。JSON就是以JavaScript对象形式书写的纯文本。它包含几个键值对,表示一些有用的信息。
需要牢记的重要事项是,尽管JavaScript以JSON的全写形式存在,但它不限于JavaScript编程语言,而是表示可以在任何编程语言、库或框架中使用的信息。多个编程环境具有解析和生成JSON数据的功能。
JSON的一些特点:
- 易于编写和紧凑,能够自我描述。
- 机器和人类都可以理解。
- 纯粹是一个字符串。
- 可以是数字、字符串、值、对象或数组,但最常用的是后两者。
- 与JavaScript对象不同,JSON中的键不能包含方法,只允许属性。
- 只能使用双引号将字符串或属性包装在JSON中。
- 我们可以通过编写.json扩展名来创建JSON文件。
- 媒体类型是application/json。
JSON的用途:
- 在Web应用程序中,用于在服务器和客户端之间传输数据。
- 通过任何软件(如Postman)测试REST API。
- 在两个或多个不同的编程环境之间交换数据。
- 用于在网络上传输和接收结构化数据。
示例
对象JSON: 这是一个包含geeks for geeks信息的简单对象。
JavaScript
{
"name": "GeeksforGeeks",
"about": "A portal for Computer Science Geeks to read the articles related",
"additionalDescription": "It also provides some Courses",
"founder": "Sandeep Jain",
"mail": "feedback@geeksforgeeks.org",
"address": "Sector-136, Noida, Uttar Pradesh - 201305"
}
数组JSON: 这是一个简单的JSON数组,包含着geeks for geeks的几门课程的列表。
Javascript
[
{
"name": "Data Structures with C++ Live",
"description": "A course specially designed for C++ enthusiasts",
"whatYouWillLearn": [
"Mastering DS from basic to advanced level",
"Solving problems which are asked in product-based companies",
"How to become a strong and efficient problem solver",
"Enhance your problem-solving ability"
]
},
{
"name": "JAVA Backend Development - Live",
"description": "Learn backend development with Hibernate, RESTful APIs",
"whatYouWillLearn": [
"Redis & Kafka with Spring Boot",
"Advanced Java",
"Spring / Spring Boot",
"Micro-services & related technologies used to build Java-based web applications"
]
},
{
"name": "System Design - Live",
"description": "LIVE System Design classes for individuals looking to crack SDE job",
"whatYouWillLearn": [
"How to design scalable systems",
"Tips to crack system design interviews",
"The intensity of the interview & how to manage your time",
"Real-world example questions like designing system of Uber, Twitter etc.",
"How to apply theory into application in real-time"
]
}
]
在Javascript中的JSON: 在javascript中,我们可以简单地使用javascript的内置stringify()方法 创建JSON。
Javascript
<script>
const myObject = {
a:1,
b:"Some Text",
c:[
{
key1:"property1"
},
{
key2:"property2"
},
{
key3:"property3"
}
]
};
console.log(JSON.stringify(myObject));
</script>
输出:- 当我们在浏览器中打开包含上述代码段的index.html文件时,这将在控制台中发生。