简体   繁体   English

React Native JSON 解析错误意外的标识符

[英]React Native JSON Parse error Unexpected identifier

I'm trying to get the location from my cellphone and then send it to an API, so far everything works well untill I try to access each individual value of the data.我正在尝试从我的手机获取位置,然后将其发送到 API,到目前为止一切正常,直到我尝试访问数据的每个单独值。

So far this is my code.到目前为止,这是我的代码。

import React, { useEffect, useState} from "react";
import { StyleSheet, View, Text, TouchableOpacity } from "react-native";
import MapView, { Marker }from "react-native-maps";

import * as Location from 'expo-location';
import * as Permissions from 'expo-permissions';

const Untitled1 = (props) => {

  const [errorMessage, setError] = useState(null);
  const [location, setLocation] = useState(null);

  useEffect(() => { 
   (async () => {
    let { status } = await Permissions.askAsync(Permissions.LOCATION);
    if (status !== 'granted') {
      setError({
        errorMessage: 'Ubication service was denied',
      });
    }
    let location = await Location.getCurrentPositionAsync({accuracy:Location.Accuracy.Highest});
    setLocation(location);
   })();
  });

  let valor = 'waiting...';
  if(errorMessage) {
    valor = errorMessage;
  }else if(location){
    valor = JSON.stringify(location);
  }

  reporte = JSON.parse(valor);
  console.log(valor);

  return (
    <View style={styles.container}>
      <Text style={styles.latitud}></Text>
      <Text style={styles.longitud}></Text>
      <Text style={styles.velocidad}></Text>
      <Text style={styles.direccion}></Text>
      <Text style={styles.ciudad}></Text>
      <Text style={styles.calle}></Text>
      <Text style={styles.heading2}>{errorMessage}</Text>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  mapView: {
    height: 338,
    width: 657,
    marginLeft: -108
  },
  latitud: {
    fontFamily: "roboto-regular",
    color: "#121212",
    marginTop: 64,
    marginLeft: 45
  },
  longitud: {
    fontFamily: "roboto-regular",
    color: "#121212",
    marginLeft: 45
  },
  velocidad: {
    fontFamily: "roboto-regular",
    color: "#121212",
    marginTop: 26,
    marginLeft: 45
  },
  direccion: {
    fontFamily: "roboto-regular",
    color: "#121212",
    marginTop: -38,
    marginLeft: 45
  },
  ciudad: {
    fontFamily: "roboto-regular",
    color: "#121212",
    fontSize: 40,
    marginTop: 58,
    marginLeft: 88
  },
  calle: {
    fontFamily: "roboto-regular",
    color: "#121212",
    fontSize: 25,
    marginLeft: 131
  }, 
    heading2:{
    color:"#fff",
    margin:5,
    fontWeight:"bold",
    fontSize:15
  },
});

export default Untitled1;

The data i recieve from my phone is presented like this.我从手机收到的数据是这样呈现的。


Object {
   "coords": Object {
      "accuracy": 15.28600025177002,
       "altitude": 2233,
       "heading": 0,
       "latitude": -------,
       "longitude": ------,
       "speed": 0,
      },
    "mocked": false,
    "timestamp": 1592163692035,
        }

And what I did is to access the data this way: valor.coords and this gives me the next object:我所做的是以这种方式访问数据: valor.coords ,这给了我下一个 object:


Object {
    "accuracy": 14.409000396728516,
    "altitude": 2233,
    "heading": 80.9710693359375,
    "latitude": -------,
    "longitude": -------,
    "speed": 0.003523211693391204,
  }

I realized that this object has a trailing comma, so is invalid, so I proceeded to stringify it and get a valid JSON so i could do a JSON.parse() , but everytime i try this error comes out.我意识到这个 object 有一个尾随逗号,所以是无效的,所以我继续对其进行字符串化并得到一个有效的 JSON 所以我可以做一个JSON.parse() ,但是这个错误每次都会出现。


SyntaxError: SyntaxError: JSON Parse error: Unexpected identifier "waiting"

I don't really know how to proceed to with this one, so if you guys could help me, I would be more than grateful with you.我真的不知道如何继续这个,所以如果你们能帮助我,我会非常感激你们。

The problem is in here.问题就在这里。

let valor = 'waiting...';

if(errorMessage) {
  valor = errorMessage;
}else if(location){
  valor = JSON.stringify(location);
}

reporte = JSON.parse(valor);
console.log(valor);

One is, you parse waiting... to JSON.parse() which will result you in this error.一种是,您将waiting...解析为JSON.parse() ,这将导致您出现此错误。

To set the location, it takes very little time and the above code snippet is running before the location is set.设置位置只需要很少的时间,并且上面的代码片段在设置位置之前运行。 This is due to very little difference of milliseconds.这是由于毫秒的差异很小。

So, please put the above code into a useEffect and listen to the location changes.所以,请将上面的代码放入一个useEffect并监听location的变化。 Like this,像这样,

useEffect(() => {
    let valor = 'waiting...';
    let reporte = null;

    if (errorMessage) {
      valor = errorMessage;
    }
    else if (location) {
      valor = JSON.stringify(location); // If this is already stringyfied, no need to stringify it again.
      reporte = JSON.parse(valor);
    }

    console.log(valor);
  }, [location]);

So, your whole file will be as follows.因此,您的整个文件将如下所示。

import React, { useEffect, useState } from 'react';
import { StyleSheet, View, Text, TouchableOpacity } from 'react-native';
import MapView, { Marker } from 'react-native-maps';

import * as Location from 'expo-location';
import * as Permissions from 'expo-permissions';

const Untitled1 = (props) => {
  const [errorMessage, setError] = useState(null);
  const [location, setLocation] = useState(null);

  useEffect(() => {
    (async () => {
      let { status } = await Permissions.askAsync(Permissions.LOCATION);
      if (status !== 'granted') {
        setError({
          errorMessage: 'Ubication service was denied',
        });
      }
      let location = await Location.getCurrentPositionAsync({
        accuracy: Location.Accuracy.Highest,
      });
      setLocation(location);
    })();
  }, []);

  useEffect(() => {
    let valor = 'waiting...';
    let reporte = null;

    if (errorMessage) {
      valor = errorMessage;
    }
    else if (location) {
      valor = JSON.stringify(location); // If this is already stringyfied, no need to stringify it again.
      reporte = JSON.parse(valor);
    }

    console.log(valor);
  }, [location]);

  return (
    <View style={styles.container}>
      <Text style={styles.latitud}></Text>
      <Text style={styles.longitud}></Text>
      <Text style={styles.velocidad}></Text>
      <Text style={styles.direccion}></Text>
      <Text style={styles.ciudad}></Text>
      <Text style={styles.calle}></Text>
      <Text style={styles.heading2}>{errorMessage}</Text>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  mapView: {
    height: 338,
    width: 657,
    marginLeft: -108,
  },
  latitud: {
    fontFamily: 'roboto-regular',
    color: '#121212',
    marginTop: 64,
    marginLeft: 45,
  },
  longitud: {
    fontFamily: 'roboto-regular',
    color: '#121212',
    marginLeft: 45,
  },
  velocidad: {
    fontFamily: 'roboto-regular',
    color: '#121212',
    marginTop: 26,
    marginLeft: 45,
  },
  direccion: {
    fontFamily: 'roboto-regular',
    color: '#121212',
    marginTop: -38,
    marginLeft: 45,
  },
  ciudad: {
    fontFamily: 'roboto-regular',
    color: '#121212',
    fontSize: 40,
    marginTop: 58,
    marginLeft: 88,
  },
  calle: {
    fontFamily: 'roboto-regular',
    color: '#121212',
    fontSize: 25,
    marginLeft: 131,
  },
  heading2: {
    color: '#fff',
    margin: 5,
    fontWeight: 'bold',
    fontSize: 15,
  },
});

export default Untitled1;

First of all you should not use the same object when you got an error and the result of the request首先,当您收到错误和请求的结果时,您不应该使用相同的 object

SyntaxError: SyntaxError: JSON Parse error: Unexpected identifier "waiting"

This error seems to come from this, you are trying to parse but you got an error.此错误似乎来自此,您正在尝试解析但出现错误。 Secondly result is already in a JSON format so stringify and parse is not necessary, can you please provide a code snippet?其次,结果已经是 JSON 格式,因此不需要进行字符串化和解析,能否提供代码片段?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM