一、将JSON字符串为JS对象

在JS中,如果直接输入

var arr = {arr:[1,2,3]};

返回的是一个object对象 因此如果我们需要将其转换为JSON,可以用如下方式进行转换

var json = '{"arr":1}';
console.log("json的类型"+typeof json)
var json = JSON.parse(json);
console.log("json的类型="+typeof json)
console.log("json的值="+json)

在大括号{}外部加入单引号,内部的字段arr加入双引号

再进行调试输出我们可以发现

请输入图片描述

二、将JS对象转换为JSON字符串

JSON.stringify()

  • 可以将一个JS对象转换为JSON字符串
  • 需要一个js对象作为参数,会返回一个JSON字符串
var obj3 = {name:"猪八戒" , age:28 , gender:"男"};
console.log("obj3的类型="+typeof obj3);
var obj3 = JSON.stringify(obj3);
console.log("obj3的类型="+typeof obj3);

请输入图片描述

GitHub 加速计划 / js / json
18
5
下载
适用于现代 C++ 的 JSON。
最近提交(Master分支:3 个月前 )
2134cb94 * change NLOHMANN_JSON_FROM_WITH_DEFAULT to let NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT work with an empty JSON instance * fix ci_static_analysis_clang (ci_clang_tidy) * change NLOHMANN_JSON_FROM_WITH_DEFAULT to let NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT work with an empty JSON instance 2 天前
6057b31d * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * Use ubuntu-latest image to run Valgrind (#4575) * :wrench: use Clang image to run valgrind * :wrench: use Clang image to run valgrind * :wrench: use Clang image to run valgrind * :wrench: use Ubuntu image to run valgrind * Use Clang image to run iwyu (#4574) * :wrench: use Clang image to run iwyu * :wrench: use Clang image to run iwyu * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :wrench: overwork astyle call * :art: format code * :hammer: clean up 4 天前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐