Using axios to get json data

novice,
use axios to get json data

data.json section:

{
    "contacts": [
        {
            "name":"",
            "id":"pony",
            "sex":1,
            "region":" ",
            "headerimg":"",
            "momentsimg":"",
            "personalnote":"",
        },
        {
            "name":"",
            "id":"AllenZhang",
            "sex":1,
            "region":" ",
            "headerimg":"",
            "momentsimg":"",
            "personalnote":"",
        },
        {
            "name":"",
            "id":"rzf",
            "sex":1,
            "region":" ",
            "headerimg":"",
            "momentsimg":"",
            "personalnote":"",
        },
        {
            "name":"",
            "id":"tyx",
            "sex":0,
            "region":" ",
            "headerimg":"",
            "momentsimg":"",
            "personalnote":"",
        },
    ],
    "moments": [
    ],
    "dialogue": [
    ]
}

js section:

<script type="text/javascript">
    import axios from "axios"
    export default{
        data() {
                return {
                   contacts: []
        }},
        created() {
            axios.get("static/data.json").then(response => 
            {
                 this.contacts = response.data.contacts;
                 //undifine
                 console.log(this.contacts)
            });
          },
    }
</script>

the print result is undefined, but if I replace it with this.contacts = response.data;, I can print successfully.

what"s the reason? the gods ask for advice

Mar.01,2021

console.log(JSON.parse(JSON.stringify(response.data))['contacts']);

how was it solved in the end? Same problem as you.


your data.json can clearly see that it is an object. While this.contacts is initialized as an array, according to
this.contacts = response.data; / / normal, successfully print
this.contacts = response.data.contacts; / / undefined
indicates that response.data is an array, most likely an array containing data.json.
so the correct method is this.contacts = response.data [0]. Steps.
or let obj = .response.data
this.contacts = obj.contacts

Menu