简体   繁体   English

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

[英]Parsing JSON, browser sees it as an array of strings, not an array of objects

very noob Javascript question I suppose.我想非常菜鸟 Javascript 问题。 I'm building a demo where I'm parsing some SQL output from an API and would like to present this on a website.我正在构建一个演示,我正在从 API 解析一些 SQL output 并希望在网站上展示它。 However, I'm struggling to parse the output and I'm not sure what I'm doing wrong.但是,我正在努力解析 output 并且我不确定我做错了什么。
I've got this in my index.html.js :我的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();
    }
});

In my index.html I have this here:在我的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>

However, stock.id and stock.price don't seem to get parsed.但是, stock.idstock.price似乎没有被解析。 stock seems to just be a string, not a JSON object. stock似乎只是一个字符串,而不是 JSON object。
Debugging the app I can see the following as my data.调试应用程序我可以看到以下作为我的数据。

Array(5) [ "{\"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/\"}" ]

So the browser sees it as an array, but rather an array of strings it seems, not an array of JSON objects.所以浏览器将其视为一个数组,而是一个字符串数组,而不是 JSON 对象的数组。
How do I fix this?我该如何解决?

Just to understand where exactly you have to do the modification and what little mistake you did has already been pointed out in the above comments.只是为了了解您必须在哪里进行修改以及您在上面的评论中已经指出了您犯了什么小错误。

> 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/'
> 

And finally, let's do it for all.最后,让我们为所有人做这件事。

> // 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/' }
]
> 

After that you will have an access to inner elements of array.之后,您将可以访问数组的内部元素。

> // 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
> 

So just check the response.data and its type using console.log(response.data, typeof response.data) and take below decisions.因此,只需使用console.log(response.data, typeof response.data)检查response.data及其类型并做出以下决定。

If如果

  • response.data is something like ["{\"k\": \"v\"}", "\"k2\": \"v2\""] as you are printing then you have to use app.stocks = response.data.map((obj) => JSON.parse(obj)) . response.data在打印时类似于["{\"k\": \"v\"}", "\"k2\": \"v2\""] ,然后您必须使用app.stocks = response.data.map((obj) => JSON.parse(obj))
  • response.data is something like [{"k": "v"}, {"k2": "v2"}] then you just need to use app.stocks = response.data (as it's already a list of objects). response.data类似于[{"k": "v"}, {"k2": "v2"}]那么你只需要使用app.stocks = response.data (因为它已经是一个对象列表)。
  • response.data is something like '[{"k": "v"}, "k2": "v2"]' (string) as you are printing then you have to use app.stocks = JSON.parse(response.data) . response.data在打印时类似于'[{"k": "v"}, "k2": "v2"]' (string) 然后你必须使用app.stocks = JSON.parse(response.data) .

Take your decisions properly and think about your response.data , its type may be 'object' |正确做出决定并考虑您的response.data ,它的类型可能是'object' | 'string' . 'string' And use JSON.parse() to get object form, if any of your list item is in string form.并使用JSON.parse()获取 object 形式,如果您的任何列表项是字符串形式。

Problem was that the JSON I received from the server seems to be malformed.问题是我从服务器收到的 JSON 似乎格式不正确。
app.stocks = JSON.parse('['+response.data+']');
fixed this.解决了这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM