1

I am trying to read a json string and output certain fields on a html page and I am getting this error:

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

This is the json I am sending:

{
  "Order0" : {
    "user" : "Name",
    "products" : [ {
      "discription" : "freddo",
      "productName" : "sketo",
      "price" : 22.3,
      "id" : 1
    }, {
      "discription" : "frape",
      "productName" : "glyko",
      "price" : 22.3,
      "id" : 1
    }, {
      "discription" : "cappouchino",
      "productName" : "sketo",
      "price" : 22.3,
      "id" : 1
    } ],
    "id" : 0,
    "date" : null,
    "temp" : "Get"
  },
  "Order1" : {
    "user" : "Name",
    "products" : [ {
      "discription" : "freddo",
      "productName" : "sketo",
      "price" : 22.3,
      "id" : 1
    }, {
      "discription" : "frape",
      "productName" : "glyko",
      "price" : 22.3,
      "id" : 1
    }, {
      "discription" : "cappouchino",
      "productName" : "sketo",
      "price" : 22.3,
      "id" : 1
    } ],
    "id" : 0,
    "date" : null,
    "temp" : "Get"
  }
}

Thank you in advance.
[EDIT]
This is the code that will handle the json.

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script>
            var nIntervId;
            function fun() {
                nIntervId = setInterval(proxy, 2 * 1000);
            }
            function proxy() {
              $.getJSON('events', function(data) {
                var obj = JSON.parse(data);
                console.log(obj.toString());
              });
            }
            function stop() {
                clearInterval(nIntervId);
            }
        </script>

    </head>
    <body onload="fun();">
       <div id="data"></div>
    </body>
</html>

[EDIT2]

I am getting the string I want with window.alert(JSON.stringify(data)); but how do I get certain fields??

GileBrt
  • 1,830
  • 3
  • 20
  • 28
  • There's nothing wrong with the JSON as presented. Are you sure that's the JSON your browser is getting? Try debugging your code and make sure. If you want help with that, you'll need to show that code. – Heretic Monkey Jun 22 '17 at 19:01
  • 1
    There's nothing wrong with the code that you shared. Something must be mangling it between you creating it and you trying to parse it. You need to provide a [mcve] to demonstrate the problem. – Quentin Jun 22 '17 at 19:01
  • There is nothing wrong with your object. Are you calling `JSON.parse(string)` or `JSON.stringify(object)`? – vbguyny Jun 22 '17 at 19:02
  • @AtheistP3ace doing let's say window.alert(data.toString()); prints object Object. – Antonios Lampros Jun 22 '17 at 19:10
  • 1
    Yes, because toString on an object returns object Object. toString returns "[object type]", where type is the object type If you want to turn that json object into a string you need to call `JSON.stringify(data)`. – AtheistP3ace Jun 22 '17 at 19:11
  • 1
    Possible duplicate of [SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON](https://stackoverflow.com/questions/38412574/syntaxerror-json-parse-unexpected-character-at-line-1-column-2-of-the-json) – Heretic Monkey Jun 22 '17 at 19:13
  • @SinSor I updated my answer to show an example of accessing data in the object. – AtheistP3ace Jun 22 '17 at 19:18

1 Answers1

3

$.getJSON automatically parses the string so data is already an object and calling parse on it again is throwing the error.

From jQuery docs:

The success callback is passed the returned data, which is typically a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method. It is also passed the text status of the response.

Source: http://api.jquery.com/jquery.getjson/

In order to access the data in the object you can use dot notation. Looking at the example you used above here is an example:

var user = data.Order0.user;
// user variable now holds the string "Name"

You can also access it with brackets:

var user = data["Order0"]["user"];

To get products you can use the same syntax but since products is an array you need to access it by index or by looping through the values.

Index:

var order0products = data.Order0.products;
var product1 = order0products[0];
var price = product1.price;
// The price variable now holds the value 22.3

Loop:

var order0products = data.Order0.products;
var length = order0products.length;
for (var index = 0; index < length; index++) {
    console.log(order0products.price);
}
// You will see each products price for order0 in your console.
AtheistP3ace
  • 9,611
  • 12
  • 43
  • 43