zoukankan      html  css  js  c++  java
  • JSON.parse解决Unexpected token ' in JSON at position 1报错

     壹 ❀ 引

    我们知道JSON.parse能将JSON字符串转变成JS对象,但在一些转换中可能出现Unexpected token ' in JSON at position 1的错误,这是因为被转换的值不符合JSON格式而造成的。

    JSON官方明确规定,JSON数据的key与value必须使用双引号""包裹,否则在转换过程中会导致错误。

    A value can be a string in double quotes, or a number, or true or false or null, or an object or an array. These structures can be nested.

    A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.

     贰 ❀ 示例

    // 数组
    let a = '["a","b","c"]';//
    let b = "['a','b','c']";// X
    
    // 对象
    let a1 = '{"name":"听风是风","age":"26"}';//
    let b1 = "{'name':'听风是风','age':'26'}";// X
    
    console.log(JSON.parse(a))// Array
    console.log(JSON.parse(a1))// Object
    console.log(JSON.parse(b))// 报错
    console.log(JSON.parse(b1))// 报错

    若你对JSON.stringify()JSON.parse()区别有所疑惑,以及它们在实际开发中有哪些作用,欢迎阅读博主 json.stringify()的妙用,json.stringify()与json.parse()的区别 这篇文章。

    希望对你有所帮助,那么本文到此结束。

  • 相关阅读:
    line-block,white-space,overflow
    JS操作cookie
    C#的位运算
    小常识:变量的修饰符和DEMO
    JS等号的小注释
    关于谷歌浏览器的小常识
    P2568 GCD
    P2522 [HAOI2011]Problem b
    P3455 [POI2007]ZAP-Queries
    P1447 [NOI2010]能量采集
  • 原文地址:https://www.cnblogs.com/echolun/p/11720161.html
Copyright © 2011-2022 走看看