// Transform JSON data into a string
jsonString = '[{"id":"432","temperature":"1","humidity":"1","createat":"0000-00-00 00:00:00"},{"id":"433","temperature":"22.00","humidity":"48","createat":"2015-10-11 19:49:57"},{"id":"434","temperature":"22.40","humidity":"48","createat":"2015-10-11 19:52:02"},{"id":"435","temperature":"22.40","humidity":"48","createat":"2015-10-11 19:55:26"},{"id":"436","temperature":"22.00","humidity":"48","createat":"2015-10-11 19:58:50"},{"id":"437","temperature":"22.00","humidity":"48","createat":"2015-10-11 20:02:14"},{"id":"438","temperature":"22.50","humidity":"51","createat":"2015-10-11 21:23:15"},{"id":"439","temperature":"22.50","humidity":"50","createat":"2015-10-11 21:24:37"},{"id":"440","temperature":"22.50","humidity":"51","createat":"2015-10-11 21:26:17"},{"id":"441","temperature":"22.50","humidity":"51","createat":"2015-10-11 21:26:41"}]';
// Convert the stringified JSON to a JavaScript object
parsedData = JSON.parse(jsonString);
// Define the index of the object you wish to verify
index = 0;
// Check if the specified property exists
if (typeof parsedData[index].humidity !== 'undefined') {
// Assign the property if it exists
parsedData.humidity = 1;
}
// Convert the object back to a string
jsonString = JSON.stringify(parsedData);
UPDATE: Below is a function named propertyExists
:
var propertyExists = function(jsonString, id, property) {
// Parse the JSON string into a JavaScript object
parsedData = JSON.parse(jsonString);
// Check if the property exists for the given ID
for (var i = 0; i < parsedData.length; i += 1) {
if (parseInt(parsedData[i].id) === parseInt(id)) {
return (typeof parsedData[i][property] !== 'undefined');
}
}
return false;
}
// JSON data in string format
var jsonString = '[{"id":"432","temperature":"1","humidity":"1","createat":"0000-00-00 00:00:00"},{"id":"433","temperature":"22.00","humidity":"48","createat":"2015-10-11 19:49:57"},{"id":"434","temperature":"22.40","humidity":"48","createat":"2015-10-11 19:52:02"},{"id":"435","temperature":"22.40","humidity":"48","createat":"2015-10-11 19:55:26"},{"id":"436","temperature":"22.00","humidity":"48","createat":"2015-10-11 19:58:50"},{"id":"437","temperature":"22.00","humidity":"48","createat":"2015-10-11 20:02:14"},{"id":"438","temperature":"22.50","humidity":"51","createat":"2015-10-11 21:23:15"},{"id":"439","temperature":"22.50","humidity":"50","createat":"2015-10-11 21:24:37"},{"id":"440","temperature":"22.50","humidity":"51","createat":"2015-10-11 21:26:17"},{"id":"441","temperature":"22.50","humidity":"51","createat":"2015-10-11 21:26:41"}]';
console.log(propertyExists(jsonString, 432, 'humidity'));