【问题标题】:JavaScript Body.json() on response loses nested arrays响应中的 JavaScript Body.json() 丢失嵌套数组
【发布时间】:2018-09-22 09:27:18
【问题描述】:
import 'whatwg-fetch'

传入的响应如下所示(从代理中获取):

"data": {
    "category_tree": [
        {
            "category_id": "1",
            "name": "A",
            "children": [
                {
                    "category_id": 2
                    "name": "B, child of A",
                    "children": [
                        {
                            "category_id": 3,
                            "name": "C, child of B",
                        }
                    ]
                }

            ]
        }
    ]
}

处理程序的工作方式如下:

.then( response => response.json())

.then( json => dispatch({
    type: RECEIVE_DATA,
    data: json
}))

但是当 response.json() 承诺解决时,数据已经丢失了所有的嵌套数组:

"data": {
    "category_tree": [
        {
            "category_id": "1",
            "name": "A",
            "children": []
        }
    ]
}

有什么想法可以避免这种情况发生吗?

编辑:我得到的响应标头:

HTTP/1.1 200 OK
Server: nginx/1.10.2
Date: Thu, 12 Apr 2018 09:38:32 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
X-Powered-By: PHP/7.1.15

Edit2:请求代码目前如下所示:

const fetchCategories = () => {
    return dispatch => {
        dispatch({
            type: FETCH_CATEGORIES_REQUEST
        })

        return fetch(
        `${SERVICE_API_BASE_URL}/api/categorytree?ope_flg=1`)
            .then(
                response =>  response.json(),
                error => console.log("error in fetch cat", error)
            )

            .then(
                json => console.log(json) || dispatch({
                    type: FETCH_CATEGORIES_RESPONSE,
                    categories: json
                })
            )
            .catch(
                ex => console.log("parsing failed", ex)
            )
    }
}

【问题讨论】:

  • 来自文档fetch('/users.json') .then(function(response) { return response.json() }).then(function(json) { console.log('parsed json', json) }).catch(function(ex) { console.log('parsing failed', ex) }) - 检查您在控制台中获得的输出。还要注意catch
  • @TncAndrei 感谢朋友的回复,我已经编辑了问题以添加回复标题。您是否认为如果我更改了响应中的 Content-Type,我可以将其视为 JSON 吗?
  • 嗨@Daniel,对不起,我第一次使用 JSON 时弄错了。我认为您应该使用catch 块来查看是否有任何错误。修改您的代码会很有帮助
  • @TncAndrei 我添加了请求代码——有没有一个好地方可以让小提琴与 whatwg-fetch 之类的库一起工作? (catch 块没有被触发)
  • 好的,它正在工作!它最终需要的是首先被解释为文本,然后将该文本解析为 json。所以首先是response.text(),然后是JSON.parse(text)

标签: javascript reactjs xmlhttprequest


【解决方案1】:

需要首先将响应解释为文本,然后将其解析为 JSON。来自"the body mixin for the fetch API" 上的 Mozilla 文档:

Body.text() 获取一个响应流并将其读取完成。它 返回一个用 USVString (文本)解析的承诺。响应 始终使用 UTF-8 解码。

也许.json() 因某些编码问题而失败?我确实尝试将 Content-Type 更改为 Content-Type: application/vnd.api+json 但这似乎没有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-01
    • 2021-09-16
    • 1970-01-01
    相关资源
    最近更新 更多