vue json字符串怎么转成json对象
时间: 2025-01-21 15:35:08 浏览: 50
在Vue中,将JSON字符串转换为JSON对象可以使用JavaScript内置的`JSON.parse()`方法。以下是一个简单的示例:
```html
<template>
<div>
<button @click="convertJson">转换JSON字符串</button>
<p>{{ jsonObject }}</p>
</div>
</template>
<script>
export default {
data() {
return {
jsonString: '{"name": "John", "age": 30, "city": "New York"}',
jsonObject: null
};
},
methods: {
convertJson() {
try {
this.jsonObject = JSON.parse(this.jsonString);
} catch (error) {
console.error("Invalid JSON string:", error);
}
}
}
};
</script>
<style scoped>
/* Add some styles if needed */
</style>
```
在这个示例中:
1. `jsonString`是一个包含JSON数据的字符串。
2. `convertJson`方法使用`JSON.parse()`将`jsonString`转换为JSON对象,并将其赋值给`jsonObject`。
3. 当用户点击按钮时,`convertJson`方法会被调用,转换后的JSON对象会显示在页面上。
阅读全文
相关推荐


















