我有一个简单的问题。
我有多种方法可以从我无法控制的其他应用程序获取JSON。所有键都具有相同的名称,但是有些键是大写的,有些是小写的。
我如何读取JSON,所以不管是小写还是大写?
例如在我的代码中,当json的customer_id
小写时不起作用
我当前的功能不起作用。我需要一个通用函数,该函数将长度为1或更多的json对象的键转换为大写
HTML
<td ng-repeat="customer in customers">{{customer.CUSTOMER_ID}}</td> // this only works when the JSON keys comes uppercase
控制器
//another function
$http.get(baseUrl + param).then(function (response) {
console.log(response.data.items);
console.log(normalizeJSON(response.data.items));
$scope.customers = normalizeJSON(response.data.items);
});
};
function normalizeJSON (jsonObject) {
var parsedObjectWithLowerCaseKeys = {};
for(var i = 0; i < jsonObject.length; i++) {
Object.keys(jsonObject[i]).forEach(function (itemKey) {
parsedObjectWithLowerCaseKeys[itemKey.toUpperCase()] = jsonObject[itemKey];
});
return parsedObjectWithLowerCaseKeys;
}
}
response.data.items
给出
[
{
"account_id": 4,
"account_type_description": "Joint Account",
"customer_id": 4,
"first_name": "Clark",
"last_name": "Kent",
"identity_card_number": 2132142134,
"tax_identification": 2892031234,
"birth_date": "2018-06-28T07:57:23Z",
"customer_gender_description": "Male",
"street_address": "Gotham Street 56",
"postal_code": "21312",
"city": "Gotham",
"country_description": "Portugal"
},
{
"account_id": 4,
"account_type_description": "Joint Account",
"customer_id": 5,
"first_name": "Cristiano",
"last_name": "Ronaldo",
"identity_card_number": 2132142135,
"tax_identification": 2892031235,
"birth_date": "2018-06-28T07:57:23Z",
"customer_gender_description": "Male",
"street_address": "Gotham Street 56",
"postal_code": "21312",
"city": "Gotham",
"country_description": "Portugal"
}
]
编辑:不同
答案 0 :(得分:0)
如下更新功能。
function normalizeJSON (jsonObject) {
var newJsonObject = [];
for(var i = 0; i < jsonObject.length; i++) {
var parsedObjectWithLowerCaseKeys = {};
Object.keys(jsonObject[i]).forEach(function (itemKey) {
parsedObjectWithLowerCaseKeys[itemKey.toUpperCase()] = jsonObject[i][itemKey];
});
newJsonObject.push(parsedObjectWithLowerCaseKeys);
}
return newJsonObject;
}