SyntaxError:JSON中位置1处的意外令牌o

2020/11/15 04:22 · javascript ·  · 0评论

我在控制器中使用类型类解析了一些数据,如下所示:

{  
   "data":{  
      "userList":[  
         {  
            "id":1,
            "name":"soni"
         }
      ]
   },
   "status":200,
   "config":{  
      "method":"POST",
      "transformRequest":[  
         null
      ],
      "transformResponse":[  
         null
      ],
      "url":"/home/main/module/userlist",
      "headers":{  
         "rt":"ajax",
         "Tenant":"Id:null",
         "Access-Handler":"Authorization:null",
         "Accept":"application/json, text/plain, */*"
      }
   },
   "statusText":"OK"
}

我试图像这样存储数据

var userData = _data;
var newData = JSON.parse(userData).data.userList;

如何将用户列表提取到新变量?

您发布的JSON看起来不错,但是在您的代码中,它很可能不再是JSON字符串,而已经是JavaScript对象。这意味着不再需要解析。

您可以自己进行测试,例如在Chrome的控制台中:

new Object().toString()
// "[object Object]"

JSON.parse(new Object())
// Uncaught SyntaxError: Unexpected token o in JSON at position 1

JSON.parse("[object Object]")
// Uncaught SyntaxError: Unexpected token o in JSON at position 1

JSON.parse()将输入转换为字符串。toString()默认情况下,JavaScript对象方法返回[object Object],从而导致观察到的行为。

请尝试以下操作:

var newData = userData.data.userList;

函数的第一个参数JSON.parse应该是String,并且您的数据是JavaScript对象,因此它将转换为String [object object],您应该JSON.stringify在传递数据之前使用

JSON.parse(JSON.stringify(userData))

不要JSON.parse将其包装在try-catch块中使用:

// payload 
let userData = null;

try {
    // Parse a JSON
    userData = JSON.parse(payload); 
} catch (e) {
    // You can read e for more info
    // Let's assume the error is that we already have parsed the payload
    // So just return that
    userData = payload;
}

// Now userData is the parsed result

Just above JSON.parse, use:

var newData = JSON.stringify(userData)

Well, I meant that I need to parse object like this: var jsonObj = {"first name" : "fname"}. But, I don't actually. Because it's already an JSON.

Unexpected 'O' error is thrown when JSON data or String happens to get parsed.

If it's string, it's already stringfied. Parsing ends up with Unexpected 'O' error.

I faced similar( although in different context), I solved the following error by removing JSON Producer.

    @POST
    @Produces({ **MediaType.APPLICATION_JSON**})
    public Response login(@QueryParam("agentID") String agentID , Officer aOffcr ) {
      return Response.status(200).entity("OK").build();

  }

The response contains "OK" string return.
The annotation marked as @Produces({ **MediaType.APPLICATION_JSON})** tries to parse the string to JSON format which results in Unexpected 'O'.

Removing @Produces({ MediaType.APPLICATION_JSON}) works fine.
Output : OK

Beware:
Also, on client side, if you make ajax request and use JSON.parse("OK"), it throws Unexpected token 'O'

O is the first letter of the string

JSON.parse(object) compares with jQuery.parseJSON(object);

JSON.parse('{ "name":"Yergalem", "city":"Dover"}'); --- Works Fine

We can also add checks like this:

function parseData(data) {
    if (!data) return {};
    if (typeof data === 'object') return data;
    if (typeof data === 'string') return JSON.parse(data);

    return {};
}

给这样一个try catch,如果字符串化了,它将解析它,否则将采用默认值

let example;
   try {
   example  = JSON.parse(data)
  } catch(e) {
    example = data
  }
本文地址:http://javascript.askforanswer.com/syntaxerrorjsonzhongweizhi1chudeyiwailingpaio.html
文章标签: ,   ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!