N
N
Nikolay Baranenko2016-08-10 13:39:02
JavaScript
Nikolay Baranenko, 2016-08-10 13:39:02

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>


The error
Uncaught SyntaxError: Unexpected token & in JSON at position 2

is reproduced BUT if you take and copy the entire content
directly into the Java script, then everything works.

<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>


Please tell me where I'm making a mistake.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
E
Evhen, 2016-08-10
@drno-reg

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>

N
Nikolay Baranenko, 2016-08-10
@drno-reg

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 question

Ask a Question

731 491 924 answers to any question