本文介绍了迭代JSON对象字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个javascript noob。在创建json字符串之后,我有一个由google gson API创建的JSON字符串,我将它传递给我的javascript函数。所以在javascript变量中我有一个字符串如下

I am a javascript noob. I have a JSON string created by google gson API after creating the json string which I am passing it to my javascript function. So in a javascript variable I have a string as follows

'{"validationCode":"V10291","caseNumber":"2010CF101011","documentSource":"EFILE","countyDocumentID":"CD102","documentTitle":"D Title","signedDate":"01/01/2012","signedBy":"CPSJC","comments":"YES Comments"}'

如何迭代这个或得到一个关键值的东西就像我必须找到validationCode或caseNumber,但这是String?欢迎任何建议

How to iterate over this or get a value of the key something like I have to find validationCode or caseNumber, but this is String? Any suggestions are welcome

推荐答案

您可以使用 JSON.parse将其添加到本机JavaScript对象中

var obj = JSON.parse(yourJSONString);

然后你可以用循环标准迭代键

Then you can iterate the keys with a standard for in loop

for(var k in obj)
    if ({}.hasOwnProperty.call(obj, k))
        console.log(k, " = ", obj[k]);

或访问特定密钥,例如 validationCode caseNumber 直接:

Or access particular keys like validationCode or caseNumber directly:

var caseNum = obj.caseNumber;
var validationCode = obj.validationCode;






请注意,真正的旧浏览器不支持 JSON.parse ,所以如果你想支持它们,你可以使用Papa Crockford的,或者jQuery,它有一个实用程序方法。


Note that really old browsers don't support JSON.parse, so if you want to support them, you can either use Papa Crockford's json2, or jQuery, which has a parseJSON utility method.

这篇关于迭代JSON对象字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 08:10