以下场景中的Javascript代码是什么样的? 我有跟随json对象。
jsonObject= '{
"2lor": {"userID":"1","clientID":"abc123","uid":"j42d"},
"WFAR": {"userID":"2","clientID":"xyz123","uid":"V23d"}
}'
我想在json上解析。我想回来
"2lor": {"userID":"1","clientID":"abc123","uid":"j42d"}
当我的参数为"j42d"
时。
我的功能将如下所示。
function Find(uid, done) {
return done(null, value);
};
uid:“j42d”, 值(输出):
"2lor": {"userID":"1","clientID":"abc123","uid":"j42d"}
答案 0 :(得分:1)
var json_string = '{ "2lor": {"userID":"1","clientID":"abc123","uid":"j42d"}, "WFAR": {"userID":"2","clientID":"xyz123","uid":"V23d"} }';
var json = JSON.parse(json_string);
var data = json['2lor'];
// to get the uid..
var uid = data.uid;
注意,你不能在javascript字符串中使用换行符,除非你将它们转义,所以你需要将它们全部放在一行上(或者只是删除外部引号并跳过解析)。
答案 1 :(得分:1)
您需要遍历JSON对象并找到符合条件的值。
Pamblam是对的,您需要摆脱字符串中的换行符,或者将JSON构建为对象文字:
var json = {
"2lor":{
"userID":"1",
"clientID":"abc123",
"uid":"j42d"
},
"WFAR":{
"userID":"2",
"clientID":"xyz123",
"uid":"V23d"
}
};
var myResult = getByUid(json, "j42d");
function getByUid(data, uid) {
for (var key in data) {
if (data.hasOwnProperty(key) && data[key].uid === uid) {
var obj = {};
obj[key] = data[key];
return obj;
}
}
return {};
}