Answer the question
In order to leave comments, you need to log in
What is the correct way to pass JSON from JSTL to Java Script?
Hello.
I'm trying to send JSON from JSP.
<c:set var="json_text">
[{"TIME_STAMP": "2016-07-25 02:30:22", "COUNTER": "COUNT_ALL", "VALUE": 635 }, { "TIME_STAMP": "2016-07-25 02:30:22", "COUNTER": "COUNT_BAD", "VALUE": 1 }, { "TIME_STAMP": "2016-07-25 02:30:22", "COUNTER": "QUALITY", "VALUE": 99.84 }, { "TIME_STAMP": "2016-07-25 02:31:22", "COUNTER": "COUNT_ALL", "VALUE": 642 }, { "TIME_STAMP": "2016-07-25 02:31:22", "COUNTER": "COUNT_BAD", "VALUE": 1 }, { "TIME_STAMP": "2016-07-25 02:31:22", "COUNTER": "QUALITY", "VALUE": 99.84 }]
</c:set>
<script type="text/javascript">
var jsonString='<c:out value="${json_text}"/>';
var jsonObj = JSON.parse(jsonString);
</script>
<script type="text/javascript">
var jsonString='[{"TIME_STAMP": "2016-07-25 02:30:22", "COUNTER": "COUNT_ALL", "VALUE": 635 }, { "TIME_STAMP": "2016-07-25 02:30:22", "COUNTER": "COUNT_BAD", "VALUE": 1 }, { "TIME_STAMP": "2016-07-25 02:30:22", "COUNTER": "QUALITY", "VALUE": 99.84 }, { "TIME_STAMP": "2016-07-25 02:31:22", "COUNTER": "COUNT_ALL", "VALUE": 642 }, { "TIME_STAMP": "2016-07-25 02:31:22", "COUNTER": "COUNT_BAD", "VALUE": 1 }, { "TIME_STAMP": "2016-07-25 02:31:22", "COUNTER": "QUALITY", "VALUE": 99.84 }]';
var jsonObj = JSON.parse(jsonString);
</script>
Answer the question
In order to leave comments, you need to log in
JSON is a JS object, and in your case you don't need to first represent it as a string and then parse it with JSON.parse.
This is how it should be the norm.
<c:set var="json_text">
[{"TIME_STAMP": "2016-07-25 02:30:22", "COUNTER": "COUNT_ALL", "VALUE": 635 }, { "TIME_STAMP": "2016-07-25 02:30:22", "COUNTER": "COUNT_BAD", "VALUE": 1 }, { "TIME_STAMP": "2016-07-25 02:30:22", "COUNTER": "QUALITY", "VALUE": 99.84 }, { "TIME_STAMP": "2016-07-25 02:31:22", "COUNTER": "COUNT_ALL", "VALUE": 642 }, { "TIME_STAMP": "2016-07-25 02:31:22", "COUNTER": "COUNT_BAD", "VALUE": 1 }, { "TIME_STAMP": "2016-07-25 02:31:22", "COUNTER": "QUALITY", "VALUE": 99.84 }]
</c:set>
<script>
var jsonObj = ${json_text};
</script>
Thank you for your help, it worked
<script type="text/javascript">
var jsonObj = ${json_text};
var jsonResult = [];
jsonResult.push("Вывод JSON="+'<c:out value="${json_text}"/>');
jsonResult.push("количество строк json="+jsonObj.length);
result_json.innerHTML = jsonResult.join('<br>');
</script>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question