1

I am trying to read values from JSON string and display some of it's values using JavaScript alert() statement. But I am getting following exception in the console.

Please guide.

Console Exception

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
...dc=/\?/;n.parseJSON=function(a){return JSON.parse(a+"")},n.parseXML=function(a){...

at jquery.min.js(line 4, col 5304)

process.js

$(document).ready(function () {
    //for handling json data
    var json = $("#studentJsonDiv").data("students-json");
    console.log(json);
    $.each($.parseJSON(json), function (idx, obj) {
        alert(obj.name);
    });
});

home.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script src="js/process.js"></script>
    </head>
    <body>
        From JQuery (JSON): <div id="studentJsonDiv" data-students-json='${studentsJson}'></div>
    </body>
</html>

View Page Source of home.jsp

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script src="js/process.js"></script>
    </head>
    <body>
        From JQuery (JSON): <div id="studentJsonDiv" data-students-json='[{"id":1,"name":"Jack"},{"id":2,"name":"Jill"}]'></div>
    </body>
</html>
7
  • data-students-json or data-students Commented Oct 15, 2015 at 18:51
  • data-students-json. Sorry for the confusion. Commented Oct 15, 2015 at 18:54
  • then use $("#studentJsonDiv").data("students-json"); Commented Oct 15, 2015 at 18:56
  • Can you log json variable and tell what are you getting in console before the error? Add a console.log(json) before you are parsing it. Commented Oct 15, 2015 at 18:57
  • @Abhas - After doing a console.log(json) I see following: [Object { id=1, name="Jack"}, Object { id=2, name="Jill"}] Commented Oct 15, 2015 at 18:59

4 Answers 4

2

Since jQuery 1.6 the .data() method parses the values, so remove the $.parseJSON(). You are parsing the object not string that causing the error here. Also check - Why is jQuery automatically parsing my data-* attributes?

Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null). A value is only converted to a number if doing so doesn't change the value's representation. For example, "1E02" and "100.000" are equivalent as numbers (numeric value 100) but converting them would alter their representation so they are left as strings. The string value "100" is converted to the number 100.

When the data attribute is an object (starts with '{') or array (starts with '[') then jQuery.parseJSON is used to parse the string; it must follow valid JSON syntax including quoted property names. If the value isn't parseable as a JavaScript value, it is left as a string. ( Taken from https://api.jquery.com/data/ )

$(document).ready(function() {
  //static message
  var msg = "Hello World from JQuery!";
  $("#mydiv").text(msg);

  //dynamic message processing for displaying value in div element
  var students = $("#studentDiv").data("students");
  $("#studentDiv").text(students);

  //for handling json data
  var json = $("#studentJsonDiv").data("students-json");
  //     change value here ---------------^------^------

  console.log(json);
  $.each(json, function(idx, obj) {
    alert(obj.name);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="mydiv"></div>
From JQuery:
<div id="studentDiv" data-students="[Student{id=1, name=Jack}, Student{id=2, name=Jill}]"></div>
From JQuery (JSON):
<div id="studentJsonDiv" data-students-json='[{"id":1,"name":"Jack"},{"id":2,"name":"Jill"}]'></div>

Sign up to request clarification or add additional context in comments.

Comments

1

The data you get is an Array of objects. You just have to iterate over it, without having to parse it again. Also, correct attribute name.

var json = $("#studentJsonDiv").data("students-json");
$.each(json, function (idx, obj) {
    alert(obj.name);
});

Comments

0

You need to use students-json in data because that is where you have your json data

var json = $("#studentJsonDiv").data("students-json");
$.each($.parseJSON(json), function(idx, obj) {
    alert(obj.name);
});

Comments

0

If you're parsing

[Student{id=1, name=Jack}, Student{id=2, name=Jill}]

it's missing : after Student.

2 Comments

it's not a valid json :)
@Kriggs - I am trying to parse the data-students-json and not data-students. Sorry for the confusion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.