I am trying to pull the type JSON data from "0", but I'm getting a SyntaxError. In postman, part of the returned data looks like this:
var array = {
"catalogs": {
"add": {
"0": {
"type": 'catalog',
"id": '2027528',
"date_create": '1637310194',
"date_modify": '1637310194',
"created_by": '7382229',
"modified_by": '7382229',
"catalog_id": '8241',
"name": '',
"deleted": '0',
"custom_fields": {
"0": {
"id": '912743',
"name": 'Статус',
"values": {
"0": {
"value": 'Создан',
"enum": '4197277'
}
},
"code": 'BILL_STATUS'
},
"1": {
"id": '912747',
"name": 'Плательщик',
"values": {
"0": {
"value": {
"name": 'TEST TEST',
"entity_id": '63836888',
"entity_type": 'contacts'
}
}
},
"code": 'PAYER'
},
"2": {
"id": '912753',
"name": 'Позиции счета',
"values": {
"0": {
"value": {
"sku": '',
"description": '1111',
"unit_price": '1111',
"unit_type": 'шт',
"quantity": '1',
"discount": {
"type": 'amount',
"value": '0'
},
"vat_rate_id": '0',
"vat_rate_value": '20',
"bonus_points_per_purchase": '0',
"external_uid": ''
}
}
},
"code": 'ITEMS'
},
"3": {
"id": '912755',
"name": 'Комментарий',
"values": {
"0": {
"value": '1111'
}
},
"code": 'BILL_COMMENT'
},
"4": {
"id": '912757',
"name": 'Стоимость',
"values": {
"0": {
"value": '1111'
}
},
"code": 'BILL_PRICE'
}
},
"created_at": '1637310194',
"updated_at": '1637310194'
}
}
},
"account": {
"_links": {
"self": 'https://amocrm.ru'
},
"subdomain": 'mylogoped',
"id": '24809335'
}
};
When I try to use the code, I get an error (SyntaxError: Unexpected number)
var myDat = testOne.catalogs.add.0.type;
Found a solution in one of the posts, but it does not work, an error also comes out
for (let i = 0; i < testOne.catalogs.add.0.length; i ) {
var type = testOne.catalogs.add.0[i].type;
sheet.getRange(lastRow 1, 5).setValue(type);
}
Found a solution here SyntaxError: Unexpected number when pulling JSON data but it doesn't work because SyntaxError: Unexpected token '['
for (let i = 0; i < testOne.catalogs.add.["0"].length; i ) {
var type = testOne.catalogs.add.["0"][i].type;
sheet.getRange(lastRow 1, 5).setValue(type);
}
Please tell me how I can take data from the "0" array, everything behind it is pulled like this
var myData = testOne.account.subdomain;
CodePudding user response:
You have no array in the JSON data.
It is an object with nested objects. Also the .["0"]
syntax is incorrect.
You could do something like the following to iterate:
var keys = Object.keys(testOne.catalogs.add);//array of keys
for (let i = 0; i < keys.length; i ) {
var type = testOne.catalogs.add[keys[i]].type;
// ...do something
}
But it will not guarantee the order of items to be the same as you see in the data because of how the objects work. If order is important then you can sort the keys
array accordingly.