'VueJS - Composition API - How to properly import and read a local JSON file
I am having some trouble loading in a local JSON file to read some data. It seems I can get the data to import as I can log it out to the console. If I do console console.log(rooms.value) for example I get the following in chrome browser:
I want to iterate through the data, however if I try a v-for="room in rooms" and output room.id for example I just get 
Please can someone help?
JSON:
{
"rooms":[
{
"id": 1,
"name": "Master Bedroom",
"floor": 1,
"lights": true,
"blinds": true,
"climate": true,
"music": true
},
{
"id": 2,
"name": "Living Room",
"floor": 0,
"lights": true,
"blinds": true,
"climate": true,
"music": true
}
]
}
Vue:
<script>
import { ref } from 'vue'
import roomData from '../../data/db.json'
export default {
components: {},
setup(){
const rooms = ref(roomData)
console.log(rooms.value)
return { rooms }
}
}
</script>
Solution 1:[1]
you can call result of iteration with room.id not rooms.id, this might just be a typo in your template code.
Solution 2:[2]
I've worked it out - I could only access the array by assigning the constant to roomData.rooms (as opposed to just roomData). So working code looks like:
<script>
import { ref } from 'vue'
import roomData from '../../data/db.json'
export default {
components: {},
setup(){
const rooms = ref(roomData.rooms)
console.log(rooms.value)
return { rooms }
}
}
</script>
Solution 3:[3]
to import your json you can do this with SFC in vuejs3
<script setup>
import roomData from '../../data/db.json'
console.log(roomData)
</script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Muhammad Gata |
| Solution 2 | mellows |
| Solution 3 |

