首先,我知道用连字符命名数组对象是完全不正确的,我不是它的创建者。我需要在服务中调用 API,并且许多对象命名不正确,例如{"children-education": [
和{ "Kid Stories": [
。
我尝试将名称分配给像let edChild = "child-education"
这样的变量,然后将其解析为一个对象,比如edChild = JSON.parse(edChild)
无济于事。我真的不知道我在做什么,甚至不知道是否有可能这样做。
我可以选择打电话给我的客户,并恳请他的团队将对象重命名为更少的对象......比我无法在 Typescript 中调用的特殊字符更愚蠢,但我想了解是否有办法在未来的场合超越它,或者他们是否无法重命名它。
以下是我尝试迭代的 JSON 示例:
{
"business":
[
{
"anim":
[
{
"child-education": [
{
"Kid Stories": [
{
"id": 1,
"name": "Three Little Pinkies",
"url": "#",
"description": "shows how the world is beautiful"
},
(... and so on)
提前谢谢。
你可以像解析任何 JSON 字符串一样解析该 JSON 字符串,使用 JSON.parse((
let str = "{n" +
" "business":n" +
" [n" +
" {n" +
" "anim":n" +
" [n" +
" {n" +
" "child-education": [n" +
" {n" +
" "Kid Stories": [n" +
"n" +
" {n" +
" "id": 1,n" +
" "name": "Three Little Pinkies",n" +
" "url": "#",n" +
" "description": "shows how the world is beautiful"n" +
" }]}]}]}]}" +
""
console.log(JSON.parse(str));
之后,您可以使用括号表示法访问任何属性名称
let str = "{n" +
" "business":n" +
" [n" +
" {n" +
" "anim":n" +
" [n" +
" {n" +
" "child-education": [n" +
" {n" +
" "Kid Stories": [n" +
"n" +
" {n" +
" "id": 1,n" +
" "name": "Three Little Pinkies",n" +
" "url": "#",n" +
" "description": "shows how the world is beautiful"n" +
" }]}]}]}]}" +
""
const obj = JSON.parse(str);
console.log(obj.business[0].anim[0]['child-education'][0]['Kid Stories'][0]);