简体   繁体   English

如何将 JSON 数组转换为 javascript 对象数组?

[英]How to convert an array of JSON into an array of javascript object?

For example, this is the JSON array:例如,这是 JSON 数组:

    [
     {
       "name":"Jennifer Bellingham",
       "shortname":"Jenni"
     },
     {
       "name":"Jonathan G. Ferrar II",
       "shortname":"Jonathan_Ferrar"
     }
    ]

And this is the format I want it to be converted (an array of javascript object) :这是我希望它被转换的格式(JavaScript 对象数组):

    [
     {
       name : "Jennifer Bellingham",
       shortname : "Jenni"
     },
     {
        name : "Jonathan G. Ferrar II",
        shortname : "Jonathan_Ferrar"
     }
    ]

I used JSON.parse() but I get this error:我使用了JSON.parse()但我收到了这个错误:

SyntaxError: Unexpected token u in JSON at position 0语法错误:JSON 中的意外标记 u 位于位置 0

This is my code:这是我的代码:

I have an angularjs app:我有一个 angularjs 应用程序:

var app = angular.module('app', ['ngRoute','appControllers',
'ui.carousel']);

And this is my controller: (I'm trying to use angularjs ui carousel)这是我的控制器:(我正在尝试使用 angularjs ui carousel)

app.controller('uiCarousel', function($scope,$http) {
   $http.get('data/test.json').then(function(response){
        $scope.mySlides  = response.data;
        console.log("My Slides :", $scope.mySlides ); //I'm getting the result here
    });

    //But here I can't do the parsing right, 
    this.slides = JSON.parse($scope.mySlides);

});

this.slides in the code above expects this formatting :上面代码中的 this.slides 需要这种格式:

       [
         {
           name : "Jennifer Bellingham",
           shortname : "Jenni"
         },
         {
            name : "Jonathan G. Ferrar II",
            shortname : "Jonathan_Ferrar"
         }
        ]

Thanks for submitting your first question.感谢您提交第一个问题。

It is a little unclear as to what code snippet actually gives the error you reference - if you could include that snippet, it might help us to understand your problem.目前还不清楚哪些代码片段实际给出了您引用的错误 - 如果您可以包含该代码片段,它可能有助于我们理解您的问题。

It might be that you're inputting an object into JSON.parse instead of a string.可能是您将对象而不是字符串输入到JSON.parse中。

The below code works for me - I've used backticks ` to create a string literal, contains the json string I wish to parse.下面的代码对我有用 - 我使用反引号 ` 创建了一个字符串文字,包含我想要解析的 json 字符串。

const jsonString = `
    [
     {
       "name":"Jennifer Bellingham",
       "shortname":"Jenni"
     },
     {
       "name":"Jonathan G. Ferrar II",
       "shortname":"Jonathan_Ferrar"
     }
    ]
`;

const arrayOfObjects = JSON.parse(jsonString);

console.log(arrayOfObjects); // Returns the array of objects you reference

Umm... JSON and javascript objects are kinda the same (latter can contain more things like functions, getters, setters, etc...)嗯... JSON 和 javascript 对象有点相同(后者可以包含更多的东西,如函数、getter、setter 等...)

I guess you are getting confused by the object literal writting style.我猜你对对象字面量的写作风格感到困惑。 {"key": "value"} and {key: "value"} is same. {"key": "value"}{key: "value"}是一样的。

So... response.data is actually a javascript object (which is equivalent to the JSON data)所以... response.data实际上是一个javascript对象(相当于JSON数据)

Basically there's no need to parse anything...基本上没有必要解析任何东西......

 let a = [ { "name": "Jennifer Bellingham", "shortname": "Jenni" }, { "name": "Jonathan G. Ferrar II", "shortname": "Jonathan_Ferrar" } ]; let b = [ { name: "Jennifer Bellingham", shortname: "Jenni" }, { name : "Jonathan G. Ferrar II", shortname : "Jonathan_Ferrar" } ]; console.log(angular.equals(a,b));
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

And that's the reason why you getting an error because you are trying to parse an already parsed JSON string.这就是您收到错误的原因,因为您正在尝试解析已解析的 JSON 字符串。

For example look at this link: https://en.wikipedia.org/api/rest_v1/page/summary/JavaScript the response body of the api is JSON so fetching this is like fetching a .json file例如看这个链接: https : //en.wikipedia.org/api/rest_v1/page/summary/JavaScript api的响应主体是JSON所以获取它就像获取一个.json文件

Then response.data will be a javascript object... hence I can directly access response.data.extract然后response.data将是一个 javascript 对象...因此我可以直接访问response.data.extract

 angular.module("myApp", []) .controller("myCtrl", function($scope, $http) { $http .get("https://en.wikipedia.org/api/rest_v1/page/summary/JavaScript") .then(function(response) { $scope.extract = response.data.extract; }) });
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="myApp" ng-controller="myCtrl">{{extract || "loading"}}</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM