javascript - 解析 JSON,浏览器将其视为字符串数组,而不是对象数组

标签 javascript json

我想这是一个非常菜鸟的 Javascript 问题。 我正在构建一个演示,我正在解析来自 API 的一些 SQL 输出,并希望在网站上展示它。但是,我正在努力解析输出,我不确定自己做错了什么。
我的 index.html.js 中有这个:

const app = new Vue({
    el: '#app',
    data() { 
        return {
            stocks: []
        }
    },
    methods: {
        async getStocks() {
            try {
                const apiUrl = `${getAPIBaseUrl()}/api/getStocks`;
                const response = await axios.get(apiUrl);
                app.stocks = JSON.parse(JSON.stringify(response.data));
            } catch (ex) {
                console.error(ex);
            }
        }
    },
    created() {
        this.getStocks();
    }
});

在我的 index.html 中我有这个:

<div id="app" class="container">
        <h1 class="title">Stocks</h1>
        <div id="stocks">
            <div v-for="stock in stocks" class="stock">
                <transition name="fade" mode="out-in">
                    <div class="list-item" :key="stock.price">
                        <div class="lead">{{ stock.id }}: ${{ stock.price }}</div>
                    </div>
                </transition>
            </div>
        </div>
    </div>

但是,stock.idstock.price 似乎没有被解析。 stock 似乎只是一个字符串,而不是一个 JSON 对象。
调试应用程序时,我可以看到以下数据。

Array(5) [ "{\"id\":\"amzn\",\"price\": 1785.6600341796875,\"_attachments\":\"attachments/\"}", "{\"id\":\"msft\",\"price\": 138.42999267578125,\"_attachments\":\"attachments/\"}", "{\"id\":\"googl\",\“价格\”:1244.280029296875,\“_附件\”:\“附件/\”}”,“{\“id\”:\“ba\”,\“价格\”:331.05999755859375,\“_附件\”:\"attachments/\"}", "{\"id\":\"air.pa\",\"price\": 122,\"_attachments\":\"attachments/\"}"]

所以浏览器将其视为一个数组,而不是一个字符串数组,而不是一个 JSON 对象数组。
我该如何解决这个问题?

最佳答案

只是为了了解您必须在何处进行修改以及您犯了什么小错误,上面的评论中已经指出了这一点。

> var arr = [ "{\"id\": \"amzn\", \"price\": 1785.6600341796875, \"_attachments\": \"attachments/\"}", "{\"id\": \"msft\", \"price\": 138.42999267578125, \"_attachments\": \"attachments/\"}", "{\"id\": \"googl\", \"price\": 1244.280029296875, \"_attachments\": \"attachments/\"}", "{\"id\": \"ba\", \"price\": 331.05999755859375, \"_attachments\": \"attachments/\"}", "{\"id\": \"air.pa\", \"price\": 122, \"_attachments\": \"attachments/\"}" ]
undefined
> 
> item0 = arr[0]
'{"id": "amzn", "price": 1785.6600341796875, "_attachments": "attachments/"}'
> 
> item0Obj = JSON.parse(item0)
{ id: 'amzn', price: 1785.6600341796875, _attachments: 'attachments/' }
> 
> item0Obj.id
'amzn'
> item0Obj.price
1785.6600341796875
> item0Obj._attachments
'attachments/'
> 

最后,让我们为所有人做这件事。

> // Do it for all
undefined
> newArr = arr.map((str) => JSON.parse(str))
[
  {
    id: 'amzn',
    price: 1785.6600341796875,
    _attachments: 'attachments/'
  },
  {
    id: 'msft',
    price: 138.42999267578125,
    _attachments: 'attachments/'
  },
  {
    id: 'googl',
    price: 1244.280029296875,
    _attachments: 'attachments/'
  },
  { id: 'ba', price: 331.05999755859375, _attachments: 'attachments/' },
  { id: 'air.pa', price: 122, _attachments: 'attachments/' }
]
> 

之后您将可以访问数组的内部元素。

> // List out all prices
undefined
> for(let obj of newArr) {
... console.log(obj.price) // obj["price"] can also be used here
... }
1785.6600341796875
138.42999267578125
1244.280029296875
331.05999755859375
122
undefined
> 
> for(let obj of newArr) {
... console.log(obj["price"]) // obj.price can also be used here
... }
1785.6600341796875
138.42999267578125
1244.280029296875
331.05999755859375
122
undefined
> 

因此,只需使用 console.log(response.data, typeof response.data) 检查 response.data 及其类型,然后做出以下决定。

如果

  • response.data 类似于 ["{\"k\":\"v\"}", "\"k2\":\"v2\""] 在打印时,您必须使用 app.stocks = response.data.map((obj) => JSON.parse(obj))
  • response.data 类似于 [{"k": "v"}, {"k2": "v2"}] 然后你只需要使用app.stocks = response.data(因为它已经是一个对象列表)。
  • response.data 就像 '[{"k": "v"}, "k2": "v2"]' (字符串)一样打印然后你必须使用 app.stocks = JSON.parse(response.data)

正确地做出你的决定并考虑你的response.data,它的类型可能是'object' | “字符串”。并使用 JSON.parse() 获取对象形式,如果您的任何列表项是字符串形式。

关于javascript - 解析 JSON,浏览器将其视为字符串数组,而不是对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58495865/

相关文章:

javascript - Raphael.js 已弃用函数和响应式函数的替代品

javascript - jQuery - if/else on window resize (如何在 jQuery 中绑定(bind) 2 个或更多事件)

java - 在 Spring MVC 或 Spring-Boot 中返回不同类型的 ResponseEntity 的最佳方法是什么

javascript - 无法访问 Zomato API JSON 对象

Javascript 本地化错误

javascript - 哪种方式是正确的,为什么?

javascript - 将多个监听器添加到 navigator.geolocation.getCurrentPosition

javascript - Toastr 多个 div

javascript - Fullcalendar js 如何从源代码构建

php - 使用 PHP 生成 JSON