如何从js数组获取json对象

时间:2019-02-18 20:07:15

标签: javascript json

let awards = ["earth","sun","moon"];
let a = JSON.stringify(awards);
console.log(a);
Result: -["earth","sun","moon"] // no difference?

在我的数据库文本字段中,我有这个:

{"earth","sun","moon"};

更新

从这里我使用以下方法获得php数组:

$arr = json_decode($data['planets'], true);

["earth","sun","moon"]{"earth","sun","moon"}有什么区别

以及如何从js数组-{"earth","sun","moon"}中获得["earth","sun","moon"];

2 个答案:

答案 0 :(得分:1)

对象的格式为{键:值}。例如,{“ Earth”:“ Planet”}是一个对象。但是{“ Earth”,“ Planet”}不是对象。

[“ earth”,“ sun”,“ moon”]是一个字符串数组。无法将字符串数组转换为对象,因为该操作实际上没有任何意义。

您确定在数据库文本字段中没有缺少冒号吗?

答案 1 :(得分:1)

["earth","sun","moon"]{"earth","sun","moon"}之间的区别在于前者是数组,后者是集合。

var words = ["earth","sun","moon"];
var set = new Set(words) // {"earth","sun","moon"}

对于json_decode,您需要指定是否要关联数组而不是对象。这可能导致数组更改为json.decode($data['planets'], true)

中的数组的Set更改。