axios:TypeError: Cannot read properties of undefined

1. Background

Get the data from the api and find that the attribute value in the json object cannot be parsed.
The following is part of the json data:

{"content": { "[{"id" : 1 ,\n "title" : "The first blog" ,\n "content" : "This is a food blog, the red rice sausage of Guangzhou morning tea is my One of my favorite food”,\n “type” : “food”\n}]”}}

2. Solve

(1) Print the data type and find that it is string

(2) Convert to object

this.axios.get('这里是一个api').then(res=>{
    
    
	//this.resultStr是我前面自己定义的变量resultStr,用于存放返回的string类型的JOSN数据
	this.resultStr = res.data.content; //res.data是从api返回的数据内容
	console.log(typeof this,resultStr); //string
	//要将string转为object
	this.resultJSON = JSON.parse(this.resultStr);
	console.log(typeof this,resultJSON); //object
	
	//这个时候就发现可以正常解析了。title是前面定义的resultJSON对象的属性
	console.log(this.resultJSON.pop().title); //这里我猜测,是用栈来存储的
})

The console prints this.resultJSON:
insert image description here

3. Similarly, post request

When transferring data to the server, the JSON data of object type should be converted to string type

textStr = JSON.stringify({
    
    name: 'lisi', age:50});

Guess you like

Origin blog.csdn.net/qq_38432089/article/details/123882562
Recommended