Home  >  Article  >  Web Front-end  >  javascript中JSON对象与JSON字符串相互转换实例_javascript技巧

javascript中JSON对象与JSON字符串相互转换实例_javascript技巧

WBOY
WBOYOriginal
2016-05-16 15:50:301205browse

本文实例讲述了javascript中JSON对象与JSON字符串相互转换实现方法。分享给大家供大家参考。具体如下:

<script type="text/javascript">
// 根据JSON对象的属性的名称获取属性的值
var jsonObj = { name: "jxqlovejava" }; // JSON对象
console.log(jsonObj.name); // "jxqlovejava"
var jsonStr = '{ name: "jxqlovejava" }';
// JSON字符串到JSON对象方法一
var jsonObj2 = eval("(" + jsonStr + ")");
console.log(jsonObj2.name); // jxqlovejava
// JSON字符串到JSON对象方法二
var jsonObj3 = JSON.parse(jsonStr);
console.log(jsonObj3.name); // jxqlovejava
// JSON对象到JSON字符串
String jsonStr2 = JSON.stringify(jsonObj);
console.log(jsonStr2); // { name: "jxqlovejava" }
</script>

希望本文所述对大家的javascript程序设计有所帮助。

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