嗨我有一个json字符串
"{"data":[{"Id":14,"ConfigName":"Online Hrs","ConfigValue":"00:01-23:59"},{"Id":15,"ConfigName":"Offline Days","ConfigValue":"Sunday"},{"Id":0,"ConfigName":"CurrentTime","ConfigValue":"11:3"}]}"
我想查看ConfigValue
"当前时间"的ConfigName
。
目前我通过以下代码
var d = JSON.parse(data).data;
d[2].ConfigValue
但有时json字符串将是
"{"data":[{"Id":14,"ConfigName":"Online Hrs","ConfigValue":"00:01-23:59"},{"Id":0,"ConfigName":"CurrentTime","ConfigValue":"11:3"}]}"
根据上面的字符串现在,如果我想访问" CurrentTime"
我将不得不写下面的代码
var d = JSON.parse(data).data;
d[1].ConfigValue
那么有谁可以告诉如何访问它?因为数组可能随时改变,所以我不能像那样对数组索引进行硬编码。
答案 0 :(得分:1)
你在字符串内外都有相同的引号而没有转义。但也许它只发生在问题文本中。
在这种情况下,你需要检查这样的每一项:
for (var i in d) {
if (d[i].Id == 0) {
alert(d[i].ConfigName);
}
}
答案 1 :(得分:1)
您可以运行循环并检查ConfigName
的值。以下是代码
var data = '{"data":[{"Id":14,"ConfigName":"Online Hrs","ConfigValue":"00:01-23:59"},{"Id":15,"ConfigName":"Offline Days","ConfigValue":"Sunday"},{"Id":0,"ConfigName":"CurrentTime","ConfigValue":"11:3"}]}';
var d = JSON.parse(data).data;
for(var i=0; i<d.length; i++)
{
if(d[i].ConfigName === 'CurrentTime')
{
alert(d[i].ConfigValue); //Do stuff with the value.
}
}
&#13;
答案 2 :(得分:0)
你可以试试这个:
var k = {"data":[{"Id":14,"ConfigName":"Online Hrs","ConfigValue":"00:01-23:59"},{"Id":15,"ConfigName":"Offline Days","ConfigValue":"Sunday"},{"Id":0,"ConfigName":"CurrentTime","ConfigValue":"11:3"}]}
var result = $(jQuery.parseJSON(JSON.stringify(k))).each(function() {
var configName = this.ConfigName;
var configValue = this.ConfigValue;
});
console.log(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
答案 3 :(得分:0)
首先需要在“ConfigValue”等于“CurrentTime”的数组中找到对象。拥有此对象后,您只需访问其“CongigValue”属性即可。
var json1 = {"data":
[
{"Id":14,"ConfigName":"Online Hrs","ConfigValue":"00:01-23:59"},{"Id":15,"ConfigName":"Offline Days","ConfigValue":"Sunday"},{"Id":0,"ConfigName":"CurrentTime","ConfigValue":"11:3"}
]
};
var json2 = {"data":
[
{"Id":14,"ConfigName":"Online Hrs","ConfigValue":"00:01-23:59"},{"Id":0,"ConfigName":"CurrentTime","ConfigValue":"11:3"}
]
};
var currentTime = findCurrentTime( json1 );
console.log( "currentTime: " + currentTime );
var currentTime = findCurrentTime( json2 );
console.log( "currentTime: " + currentTime );
function findCurrentTime( jsonObj )
{
var filteredArray = jsonObj.data.filter(function(element){
return element.ConfigName === "CurrentTime";
});//filter()
if( filteredArray.length > 0 )
return filteredArray[0].ConfigValue;
return false;
}//findCurrentTime()