JSON与Javascript对象

时间:2018-06-28 14:48:47

标签: javascript json

如何将其转换为javascript对象?

JSON.parse()在第0行给了我意外的json,而angular.fromJson则无济于事。

或将其放入数组中。我需要知道客户的人数,并且需要javascript对象

CafeBar.builder(context)
.theme(CafeBarTheme.LIGHT)
.duration(CafeBar.Duration.MEDIUM)
.content(R.string.text)
.neutralText("Action")
//You can parse string color
.neutralColor(Color.parseColor("#EEFF41"))
//Or use color resource
.neutralColor(R.color.neutralText)
.show();

$ scope.customers给我这个json

$scope.customers = allKeysToUpperCase(response.data.items);
        console.log($scope.customers);
        console.log(JSON.parse($scope.customers)); // this gives me error
        console.log(angular.fromJson($scope.customers)); // this doesnt do anything
        console.log(angular.fromJson($scope.customers).length); // this gives undefined

2 个答案:

答案 0 :(得分:0)

所有这些都是有道理的,下面是解释:

$scope.customers是有效的javascript对象。

对于其他任何工作调用,您都必须通过JSON.stringify($scope.customers)对该对象进行编码

例如,像这样拨打电话后:

console.log(JSON.parse(JSON.stringify($scope.customers))); console.log(angular.fromJson(JSON.stringify($scope.customers))); console.log(Object.keys(angular.fromJson(JSON.stringify($scope.customers))).length);

Angular文档告诉您,它需要序列化的JSON字符串REFERENCE DOC

答案 1 :(得分:0)

经过测试

console.log(typeof $scope.customers).

并获取'object',则无需解析。

  

它是对象。但是为什么$ scope.customers.length给我未定义了?

对,它是一个对象,而不是具有length属性的数组。

您可以使用

将其转换为数组
array = Object.assign([], $scope.customers);

如果索引从零开始且没有孔。