【问题标题】:Error: "Unexpected token , in JSON at position 2" in SyntaxError: Unexpected token , in JSON at position 2错误:SyntaxError: Unexpected token , in JSON at position 2 中的“Unexpected token , in JSON at position 2”
【发布时间】:2022-01-22 01:18:58
【问题描述】:

我在使用 JSON.parse 时遇到此错误。下面是函数。我正在尝试获取项目数组中对象的值,我必须首先对其进行解析,但它显示错误。

//function for get the data
 const viewUser = async () => {
    console.log('Loading');
     try {
        const keys = await AsyncStorage.getAllKeys()
        const item = await AsyncStorage.multiGet(keys)
        const data=JSON.parse(item)
    } catch (error) {
        console.log(error, "problem")
    }
  };

这是我设置值的函数。使用 math.random 为每个用户获取唯一的密钥。

const saveUser = async () => {
    var key = Math.floor(Math.random() * 100);
    console.log('Saving');
    const userObject = {
      firstName: firstName,
      secondName: secondName,
      email: email,
    };
    await AsyncStorage.setItem(
      key,
      JSON.stringify(userObject)
    );
    console.log('saving done!');
    setFirstName('');
    setSecondName('');
    setEmail('');
  };

【问题讨论】:

    标签: json react-native


    【解决方案1】:

    AsyncStorage.multiGet(keys) 的返回值不是字符串化的 JSON,而是一个元组数组。要获取值,您需要执行以下操作:

     const viewUser = async () => {
        console.log('Loading');
         try {
            const keys = await AsyncStorage.getAllKeys()
            const items = await AsyncStorage.multiGet(keys)
            // items is an array of tuples with first value as the key and second as the value
            let data = {}
            items.forEach(item => {
              data[item[0]] = item[1]
            })
        } catch (error) {
            console.log(error, "problem")
        }
      };
    

    【讨论】:

      【解决方案2】:

      有效的 JSON 字符串必须有双引号。使用反引号将您的密钥用双引号括起来

      【讨论】:

        猜你喜欢
        • 2017-01-17
        • 2016-11-03
        • 2019-11-17
        • 2019-09-20
        • 2020-10-23
        • 1970-01-01
        • 1970-01-01
        • 2021-09-30
        • 2017-12-15
        相关资源
        最近更新 更多