从 JavasScript 读取 JSON - 无法读取未定义的 属性 '0'

Read JSON from JavasScript - Cannot read property '0' of undefined

我有一个来自 ConvertAPI 的 JSON 类似的响应:

{
   "ConversionCost":10,
   "Files":[
      {
         "FileName":"somefile_XXX.pdf",
         "FileExt":"pdf",
         "FileSize":63911,
         "FileId":"718cc1XXXXXXXXX5",
         "Url":"https://v2.convertapi.com/d/XXXXXXXXXXXXXXXXXXXXXXX/somefile_XXX.pdf"
      }
   ]
}

我在以下脚本中尝试通过 result.ConversionCost[0]result.files[0].Url 工作正常)提取 ConversionCost:

let convertApi = ConvertApi.auth({secret: '<API_SECRET>'})
let elResult = document.getElementById('result')
let elResultLink = document.getElementById('resultLink')
let elUrl = document.getElementById('urlInput')
elResult.style.display = 'none'

// On file input change, start conversion
document.getElementById('convertBtn').addEventListener('click', async e => {
    elResult.style.display = 'none'
    document.documentElement.style.cursor = 'wait'
    try {

        // Converting web page to PDF file
        let params = convertApi.createParams()
        params.add('url', elUrl.value)
        params.add('FileName', 'The_FileName.pdf');
        params.add('LoadLazyContent', 'true');
        params.add('Zoom', '1.5');
        params.add('PageSize', 'a4');
        params.add('MarginTop', '0');
        params.add('MarginRight', '0');
        params.add('MarginBottom', '0');
        params.add('MarginLeft', '0');
        let result = await convertApi.convert('web', 'pdf', params)


        fetch('some_page.asp?id=315&initials=DDD&pdf_url=' + result.files[0].Url + '&ConversionCost= ' + result.ConversionCost[0]).then(function(response) {
          return response.json();
        }).then(function(data) {
          console.log(data);
        }).catch(function() {
          console.log("Booo");
        });

        // Showing link with the result file
        elResultLink.setAttribute('href', result.files[0].Url)
        elResultLink.innerText = result.files[0].Url
        elResult.style.display = 'block'

    } finally {
        document.documentElement.style.cursor = 'default'

    }
})

但这给了我控制台中的错误 Uncaught (in promise) TypeError: Cannot read property '0' of undefined at HTMLButtonElement.<anonymous>

我是不是看错了或者我错过了什么? .. 这是 GitHub vor ConvertAPI JS:https://github.com/ConvertAPI/convertapi-js

result.ConversionCost 是数字类型,但您已将其用作数组

根据您在上面给出的回复,

名为 Files 的索引尝试使用 result.Files[0].Url

也许会奏效。 :)

试试这个(代码未测试):

fetch('includes/save_user_welcomeletter_to_server.asp?id=315&initials=DDD&pdf_url=' + result.files[0].Url + '&pdf_ConversionCost= ' + result.ConversionCost)
.then(r => r.json())
.then(o => { 
    // Showing link with the result file
    elResultLink.setAttribute('href', o.files[0].Url)
    elResultLink.innerText = o.files[0].Url
    elResult.style.display = 'block'
    console.log(o.ConversionCost);
})