Have you ever needed to filter out a JSON and get only the values that you want. Try with following JavaScript application. Definitely you will need many customization.
<html>
<head>
<script language="javascript">
var jsObject = null;
//Function to convert the json string to javascript object
function extractFromJson(jsonText){
jsObject = JSON.parse(jsonText);
}
//Function to filter out values under a specific property
function filterjsObject(key){
if(key != ""){ //if object has multiple properties
var object = jsObject[key];
}else{ //if object is single
var object = jsObject;
}
var combinedValues = "";
for(var key in object){
combinedValues = combinedValues + object[key] + '<br>';
}
console.log(combinedValues);
document.getElementById('plainJsonValues').innerHTML = combinedValues;
}
//Function to get JSON key list
function getJsonKeys(jsonString){
var select = document.getElementById("jsonProperties");
var jsonString = JSON.parse(document.getElementById('jsonString').value);
var jsonKeys = Object.keys(jsonString);
console.log(jsonString);
var properties = "";
for(var i = 0; i < jsonKeys.length; i++) {
properties = properties + jsonKeys[i] + '<br>';
}
document.getElementById('jsonProperties').innerHTML = properties;
}
//Function execution point
function execute(){
extractFromJson(document.getElementById('jsonString').value);
filterjsObject(document.getElementById('jsonKey').value);
getJsonKeys(document.getElementById('jsonString').value);
}
</script>
</head>
<body>
<p>JSON String : </p>
<textarea id="jsonString" cols="80" rows="10"></textarea> <br>
<p>JSON property (Optional) : </p>
<input type="text" id="jsonKey"><br><br>
<input type="button" onClick="execute()" value ="Process"><br>
<p>JSON properties : </p>
<p id="jsonProperties"></p>
<p>Values for selected properties : </p>
<p id="plainJsonValues"></p>
</body>
</html>
No comments:
Post a Comment