Ошибка при попытке разобрать мой json

Я использую AngularJs, делающий простое приложение. Я хочу установить переменную в файле javascript в orther, чтобы вызвать json файл.

Это мой data.js:

   [{
    var data = require('data_old.json');
    var json = JSON.parse(data);

    alert(json["date"]); //01/05/2016
    alert(json.date); //01/05/2016

        "name": "city A",
        "elements": [{
          "id": "c01",
          "name": "name1",
          "price": "15",
          "qte": "10"
        }, {
          "id": "c02",
          "name": "name2",
          "price": "18",
          "qte": "11"
        }, {
          "id": "c03",
          "name": "name3",
          "price": "11",
          "qte": "14"
        }],
        "subsities": [{
          "name": "sub A1",
          "elements": [{
            "id": "sub01",
            "name": "nameSub1",
            "price": "1",
            "qte": "14"
          }, {
            "id": "sub02",
            "name": "nameSub2",
            "price": "8",
            "qte": "13"
          }, {
            "id": "sub03",
            "name": "nameSub3",
            "price": "1",
            "qte": "14"
          }]
        }, {
          "name": "sub A2",
          "elements": [{
            "id": "ssub01",
            "name": "nameSsub1",
            "price": "1",
            "qte": "7"
          }, {
            "id": "ssub02",
            "name": "nameSsub2",
            "price": "8",
            "qte": "1"
          }, {
            "id": "ssub03",
            "name": "nameSsub3",
            "price": "4",
            "qte": "19"
          }]
        }, {
          "name": "sub A3",
          "elements": [{
            "id": "sssub01",
            "name": "nameSssub1",
            "price": "1",
            "qte": "11"
          }, {
            "id": "sssub02",
            "name": "nameSssub2",
            "price": "2",
            "qte": "15"
          }, {
            "id": "sssub03",
            "name": "nameSssub3",
            "price": "1",
            "qte": "15"
          }]
        }]
      }, {
        "name": "city B",
        "elements": [{
          "id": "cc01",
          "name": "name11",
          "price": "10",
          "qte": "11"
        }, {
          "id": "cc02",
          "name": "name22",
          "price": "14",
          "qte": "19"
        }, {
          "id": "cc03",
          "name": "name33",
          "price": "11",
          "qte": "18"
        }]
      }, {
        "name": "city C",
        "elements": [{
          "id": "ccc01",
          "name": "name111",
          "price": "19",
          "qte": "12"
        }, {
          "id": "ccc02",
          "name": "name222",
          "price": "18",
          "qte": "17"
        }, {
          "id": "ccc03",
          "name": "name333",
          "price": "10",
          "qte": "5"
        }]
      }]

И это мои data.json

[{
    "date":"01/05/2016"
}]

Я вызываю свои данные здесь.

angular.module("myApp",['zingchart-angularjs'])
       .controller('MainController', ['$scope', '$http', function($scope, $http) {
          $scope.chartBase = {
            "type": "line",
            "plotarea": {
              "adjust-layout": true /* For automatic margin adjustment. */
            },
            "scale-x": {
              "label": { 
                "text": "Above is an example of a category scale" /* Add a scale title with a label object. */
              },
              "labels": ["name1", "name2", "name3"] /* Add your scale labels with a labels array. */
            },
            "series": [{
                "values": [15, 18, 11] //here the prices of city selected
              },{
                "values": [10, 11, 14] //here the qte of city selected
              }]
          };
          $scope.chartData = angular.copy($scope.chartBase);

          $http.get('data.js')
               .then(function(response) {
                 $scope.cities = response.data; // save the request data
                 $scope.selectedCity = $scope.cities[0]; // select the first one
                 $scope.changeCity(); // update chart
                }, function(error) { console.log(error); });

          $scope.changeCity = function() {
            if($scope.selectedSubCity || $scope.selectedCity){ // if something has been selected
                $scope.data = ($scope.selectedSubCity || $scope.selectedCity).elements; // update elements field

                // initialize the array to be displayed in chart
                var labels = [];
                var price = {
                  "values": []
                };
                var qte = {
                  "values": []
                };

                // fill the arrays to be displayed from the selected city (sub city)
                angular.forEach($scope.data, function(item, index) {
                  labels.push(item.name);
                  price.values.push(parseInt(item.price));
                  qte.values.push(parseInt(item.qte));
                });

                console.log($scope.chartData)

                // put selected values to the field that is used to render the chart
                $scope.chartData["scale-x"].labels = labels;
                $scope.chartData.series = [ price, qte ];
            }
          }
       }]);

Когда я запустил это, браузер сообщит, что у меня есть эта ошибка:

SyntaxError: Неожиданный токен v в JSON в позиции 5     в Object.parse(native)

Ответ 1

В вашем файле data.js их нельзя использовать, поскольку они недействительны JSON

var data = require('data_old.json');
var json = JSON.parse(data);

alert(json["date"]); //01/05/2016
alert(json.date); //01/05/2016

Ошибка указывает на первый "v" "var". Вы можете проверить свой JSON здесь http://json.parser.online.fr/ на каком-то другом онлайн-валидаторе. Ваш файл должен выглядеть следующим образом:

[{
        "name": "city A",
        "elements": [{
          "id": "c01",
          "name": "name1",
          "price": "15",
          "qte": "10"
        }, {
          "id": "c02",
          "name": "name2",
          "price": "18",
          "qte": "11"
        }, {
          "id": "c03",
          "name": "name3",
          "price": "11",
          "qte": "14"
        }],
        "subsities": [{
          "name": "sub A1",
          "elements": [{
            "id": "sub01",
            "name": "nameSub1",
            "price": "1",
            "qte": "14"
          }, {
            "id": "sub02",
            "name": "nameSub2",
            "price": "8",
            "qte": "13"
          }, {
            "id": "sub03",
            "name": "nameSub3",
            "price": "1",
            "qte": "14"
          }]
        }, {
          "name": "sub A2",
          "elements": [{
            "id": "ssub01",
            "name": "nameSsub1",
            "price": "1",
            "qte": "7"
          }, {
            "id": "ssub02",
            "name": "nameSsub2",
            "price": "8",
            "qte": "1"
          }, {
            "id": "ssub03",
            "name": "nameSsub3",
            "price": "4",
            "qte": "19"
          }]
        }, {
          "name": "sub A3",
          "elements": [{
            "id": "sssub01",
            "name": "nameSssub1",
            "price": "1",
            "qte": "11"
          }, {
            "id": "sssub02",
            "name": "nameSssub2",
            "price": "2",
            "qte": "15"
          }, {
            "id": "sssub03",
            "name": "nameSssub3",
            "price": "1",
            "qte": "15"
          }]
        }]
      }, {
        "name": "city B",
        "elements": [{
          "id": "cc01",
          "name": "name11",
          "price": "10",
          "qte": "11"
        }, {
          "id": "cc02",
          "name": "name22",
          "price": "14",
          "qte": "19"
        }, {
          "id": "cc03",
          "name": "name33",
          "price": "11",
          "qte": "18"
        }]
      }, {
        "name": "city C",
        "elements": [{
          "id": "ccc01",
          "name": "name111",
          "price": "19",
          "qte": "12"
        }, {
          "id": "ccc02",
          "name": "name222",
          "price": "18",
          "qte": "17"
        }, {
          "id": "ccc03",
          "name": "name333",
          "price": "10",
          "qte": "5"
        }]
      }]

Ответ 2

var data = require('data_old.json');
var json = JSON.parse(data);

alert(json["date"]); //01/05/2016
alert(json.date); //01/05/2016

Почему вы добавляете их в начале JSON? Они не могут быть проанализированы вашим script, таким образом отображая Синтаксическую ошибку. Что вы хотите сделать точно?