JavaScript学习笔记(一):JSON数据处理


前言 :JSON 是轻量级的文本数据交换格式,最常在前端和API数据交互中使用。这里列出一些我常用到的json数据处理方法,共勉哈 ❤

1、JSON遍历

const test = {
	name: 'mio',
	age: 18,
	type: 'girl'
};

for (const key in test) {
	if (test.hasOwnProperty(key)) {
		const element = test[key];
		console.log("属性:" + key);
		console.log("属性值:" + element);
	}
}

控制台打印结果:
在这里插入图片描述

2、JSON处理

const testJson = {
 	name: 'mio'
}

console.log('取name属性值:' + testJson.name);                  // 取有明确定义的属性值
testJson['age'] = 18;                                          // 创建一个不存在的属性
console.log('取没有明确定义的属性age值:' + testJson['age']);    // 可以取到没有明确定义的属性值

控制台打印结果:
在这里插入图片描述

3、JSON转换

① JSON转 string 格式:stringify()

const testJson = {
  name: 'mio',
  age: 18
}

const jsonToString = JSON.stringify(testJson);
console.log('原始json:');
console.log(testJson);
console.log('转换成String后:');
console.log(jsonToString);

控制台打印结果:
在这里插入图片描述

② string 还原 JSON格式:parse()

const testJson = {
  name: 'mio',
  age: 18
}

const jsonToString = JSON.stringify(testJson);
console.log('原始json:');
console.log(testJson);
console.log('转换成String后:');
console.log(jsonToString);
const stringToJson = JSON.parse(jsonToString);
console.log('String还原成Json后:');
console.log(stringToJson);

控制台打印结果:
在这里插入图片描述
备注:
同样适用于数组,代码如下:

const testArry = ['mio','neeko','abby'];
const arryToString = JSON.stringify(testArry);
console.log('原始数组:');
console.log(testArry);
console.log('转换成String后:');
console.log(arryToString);
const stringToArry = JSON.parse(arryToString);
console.log('String还原成数组后:');
console.log(stringToArry);

控制台打印结果:
在这里插入图片描述

发布了7 篇原创文章 · 获赞 12 · 访问量 2272

猜你喜欢

转载自blog.csdn.net/weixin_44104809/article/details/104008524