《html》中怎么解析json数据?

html-css015

《html》中怎么解析json数据?,第1张

HTML5已原生支持json的解析,window.JSON.parse()将json格式字符串转换为json对象,window.JSON.stringify()将json对象转换为json格式字符串。

示例:

Html代码 

<!DOCTYPE HTML>  

<html>  

<head>  

    <title>Window.JSON</title>  

    <meta charset="gb18030">  

</head>  

  

<body>  

    <button type="button" id="btn1">解析json字符串</button>  

    <button type="button" id="btn2">json对象转换为json字符串</button>  

    <div id="res">  

      

    </div>  

    <script language="JavaScript">  

    <!--  

        var jsonStr = "{\"total\":100,\"data\":[{\"id\":10001,\"name\":\"scott\"},{\"id\":10002,\"name\":\"tiger\"}]}"  

        var jsonObj = window.JSON.parse(jsonStr)  

          

        document.getElementById("btn1").onclick = function() {  

            var str = "json字符串解析为json对象<br>"  

            str += "<span>Total:"+jsonObj.total+"</span><br><span>Data:"  

            for (var i=0i<jsonObj.data.length  i++)  

            {  

                str += "id:" + jsonObj.data[i].id + ",name:" + jsonObj.data[i].name+"<br>"  

            }  

            str += "</span><br>"  

            document.querySelector("#res").innerHTML = str  

  

        }  

        document.getElementById("btn2").onclick = function() {  

            var jsonObj = {total:100,data:[{id:10001,name:"scott"},{id:10002,name:"tiger"}]}  

            var jsonStr = window.JSON.stringify(jsonObj)  

            var str = "转为json字符串:<br>" + jsonStr  

            document.querySelector("#res").innerHTML = str  

        }  

    //-->  

    </script>  

</body>  

</html>

单击“解析json字符串”按钮,结果:

json字符串解析为json对象

Total:100

Data:id:10001,name:scott

id:10002,name:tiger

单击“json对象转换为json字符串”按钮,结果:

转为json字符串:

{"total":100,"data":[{"id":10001,"name":"scott"},{"id":10002,"name":"tiger"}]}

C#如何将php序列化后的字符串转成json字符串 只需要html转码就行了 System.Web.HttpUtility.HtmlEncode(HtmlDecode)方法对字符进行编码(解码)的答题不易,互相理解,您的采纳是我前进的动力,感谢您。希望回答对你有帮助,如果有疑问,请继续追问

<html>

<head>

<meta http-equiv=content-type content="text/htmlcharset=GBK">

</head>

<body>

<table border=0 cellspacing=0 cellpadding=0>

<tr>

<td id="a">sdfsd</td>

</tr>

<tr>

<td id="b">sdfsdf</td>

</tr>

<tr>

<td id="c">sdfsd</td>

</tr>

<tr>

<td id="d">sdfsdf</td>

</tr>

</table>

</body>

<script>

var jsonStr = "{\"a\":\"内容1\", \"b\":\"内容2\",\"c\":\"内容3\",\"d\":\"内容4\"}"

var jsonObj = eval("(" + jsonStr + ")")

for(var property in jsonObj){

var nodeObj = document.getElementById(property)

if(nodeObj)

nodeObj.childNodes[0].nodeValue = jsonObj[property]

}

</script>

</html>