0

Есть скрипт Google Apps Script

function IMPORTJSON(url, xpath) {
  try {
    var res = UrlFetchApp.fetch(url);
    var content = res.getContentText();
    var json = JSON.parse(content);

    var patharray = xpath.split('/');
    // Logger.log(patharray);

    for (var i = 0; i < patharray.length; i++) {
      json = json[patharray[i]];
    }

    // Logger.log(typeof(json));

    if (typeof json === 'undefined') {
      return 'Node Not Available';
    } else if (typeof json === 'object') {
      var tempArr = [];

      for (var obj in json) {
        if (json.hasOwnProperty(obj)) tempArr.push([obj, json[obj]]);
      }
      return tempArr;
    } else if (typeof json !== 'object') {
      return json;
    }
  } catch (err) {
    return 'Error getting data';
  }
}

Он работает прекрасно, но столкнувшись с JSON массивом, он перестает работать. Пример: https://api.iextrading.com/1.0/stock/aapl/dividends/ytd

Я подозреваю что это из за скобок []

Пример: [{"exDate":"2018-02-09","paymentDate":"2018-02-15","recordDate":"2018-02-12","declaredDate":"2018-02-01","amount":0.63,"flag":"","type":"Dividend income","qualified":"Q","indicated":""}]

Как заставить его работать с такими данными ?

2
  • 1
    Что значит, он перестает работать? Какие-то ошибки или что? 6 мар 2019 в 4:27
  • oshliaer дал верный ответ, Спасибо!
    – Andrey
    9 мар 2019 в 18:47

1 ответ 1

0

Укажите позицию элемента в массиве

= IMPORTJSON(
  "https://api.iextrading.com/1.0/stock/aapl/dividends/ytd";
  "0"
)

|       A      |        B        |
|:------------:|:---------------:|
| exDate       | 2018-02-09      |
| paymentDate  | 2018-02-15      |
| recordDate   | 2018-02-12      |
| declaredDate | 2018-02-01      |
| amount       | 0.63            |
| flag         |                 |
| type         | Dividend income |
| qualified    | Q               |
| indicated    |                 |

= IMPORTJSON(
  "https://api.iextrading.com/1.0/stock/aapl/dividends/ytd";
  "0/paymentDate"
)

|      A     |
|:----------:|
| 2018-02-15 |

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.