Ошибка json parse error unrecognized token

Non of the Above mentioned answers worked for me.Infact When I was fetching the api it was done correctly like

      fetch('https://reactnative.dev/movies.json')
        .then((response) => response.json())
        .then((json) => {
          console.log(json.movies);
          
        })
        .catch((error) => {
          console.error(error);
        });

but the problem was that when I tried to add the one more string in fetch i got an error like this was the code

   const fetchCities = (text) => {
        setCity(text)
        fetch('https://reactnative.dev/movies.json'+text)
        .then((response) => response.json())
        .then((json) => {
          console.log(json.movies);
          
        })
        .catch((error) => {
          console.error(error);
        });
    }

Actually I wanted to make a searchable component so I added the following chracters to remove the error so that it can combine a string to filter the data as it is searched.

?query=

in fetch statement like this

   const fetchCities = (text) => {
        setCity(text)
        fetch('https://reactnative.dev/movies.json?query=')
        .then((response) => response.json())
        .then((json) => {
          console.log(json.movies);
          
        })
        .catch((error) => {
          console.error(error);
        });
    }

The complete code that will show the filtering effect on console as you will search for a value is given below

import { text } from '@fortawesome/fontawesome-svg-core';
import React, { Component, Fragment, useState, useEffect } from 'react';
import { FlatList,SafeAreaView, StyleSheet, ScrollView, View, Text, StatusBar, Button, Image, TextInput } from 'react-native';
import BRAND_DRUG_UNIQUE from '../BRAND_DRUG_UNIQUE.json';



const Search = () => {
    const [city, setCity] = useState("")
    const [cities, setCities] = useState([])
    const fetchCities = (text) => {
        setCity(text)
        fetch('https://reactnative.dev/movies.json?query='+text)
        .then((response) => response.json())
        .then((json) => {
          console.log(json.movies);
          
        })
        .catch((error) => {
          console.error(error);
        });
    }
    useEffect(()=>{
        
        // console.log("filteredData==> ",city);
    })
    return (
        <View style={{
            position: "relative", zIndex: 1000, borderWidth: 1, borderColor: "grey", shadowColor: "#000", marginBottom: 10,
            shadowOffset: {
                width: 0,
                height: 12,
            },
            shadowOpacity: 0.58,
            shadowRadius: 16.00,

            elevation: 24,
        }}>
            <View>
                <Text>
                    It is the search component
                </Text>
                <TextInput
                    placeholder="Search here if you want"
                    style={{ color: "#00aaff" }}
                    value={city}
                    onChangeText={(text) => fetchCities(text)}
                />
            </View>
        </View>
    );
}
export default Search;

Hope it helped.Thanks.

This is what i get as logs
Error occurs at response.json() call. Interesting thing is, this call works fine if i set chrome remote debug on. It works fine in iOS 10.0 (didn’t test in earlier version)

11-01 08:53:27.036 32587  4288 I ReactNativeJS: { type: 'default',
11-01 08:53:27.036 32587  4288 I ReactNativeJS:   status: 200,
11-01 08:53:27.036 32587  4288 I ReactNativeJS:   ok: true,
11-01 08:53:27.036 32587  4288 I ReactNativeJS:   statusText: undefined,
11-01 08:53:27.036 32587  4288 I ReactNativeJS:   headers: 
11-01 08:53:27.036 32587  4288 I ReactNativeJS:    { map: 
11-01 08:53:27.036 32587  4288 I ReactNativeJS:       { date: [ 'Tue, 01 Nov 2016 03:23:21 GMT' ],
11-01 08:53:27.036 32587  4288 I ReactNativeJS:         server: [ 'Microsoft-HTTPAPI/2.0' ],
11-01 08:53:27.036 32587  4288 I ReactNativeJS:         'content-type': [ 'application/json' ],
11-01 08:53:27.036 32587  4288 I ReactNativeJS:         'content-length': [ '187' ] } },
11-01 08:53:27.036 32587  4288 I ReactNativeJS:   url: 'http://xx.xx.xx.xx/Service/json/xxxx',
11-01 08:53:27.036 32587  4288 I ReactNativeJS:   _bodyInit: '{rn  "Command": 20020,rn  "Id": 216,rn  "Name": "Tester",rn  "Email": "cc@cc.com",rn  "Tel": "(012) 345-6712",rn  "Pass": null,rn  "IsActive": true,rn  "HasAccount": falsern}',
11-01 08:53:27.036 32587  4288 I ReactNativeJS:   _bodyText: '{rn  "Command": 20020,rn  "Id": 216,rn  "Name": "Tester",rn  "Email": "cc@cc.com",rn  "Tel": "(012) 345-6712",rn  "Pass": null,rn  "IsActive": true,rn  "HasAccount": falsern}' }

Above is the response which i get from the API call

11-01 08:53:27.042 32587  4288 I ReactNativeJS: { [SyntaxError: JSON Parse error: Unrecognized token '?']
11-01 08:53:27.042 32587  4288 I ReactNativeJS:   line: 30380,
11-01 08:53:27.042 32587  4288 I ReactNativeJS:   column: 10,
11-01 08:53:27.042 32587  4288 I ReactNativeJS:   sourceURL: 'http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=true&minify=false' }

Problem Description:

“JSON Parse error: Unrecognized token'<‘” Error is showing while hitting the api.
Code is attached below
Note* : Response is in the JSON format.

fetch("http:/example.com", {method: "POST",
  body: JSON.stringify(
    {
      uname: uname,
      password: password      
    }
  )
})
.then((response) => response.json())
.then((responseData) => {
  AlertIOS.alert(
      "POST Response",
      "Response Body -> " + JSON.stringify(responseData.body)
  )
}).done();
       this.props.navigation.navigate("Home")
   };

Please help.
Thanks,

Solution – 1

You can try by adding the headers to your fetch api, as it posts your record to your url.

var dataObj = {}
dataObj.uname = uname,
dataObj.password = password

fetch("http:/example.com", {
  method: 'post',
  headers: {
    'Accept': 'application/json, text/plain, */*',  // It can be used to overcome cors errors
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(dataObj)
})
.then((response) => response.json())
.then((responseData) => {
  AlertIOS.alert(
      "POST Response",
      "Response Body -> " + JSON.stringify(responseData.body)
  )
}).done();
    this.props.navigation.navigate("Home")
};

Solution – 2

Finally The below code worked. The problem was with Body parameters.

fetch("http:/example.com", {method: "POST",
  body: "uname=value1&password=value2" // <-- Post parameters        
})
.then((responseData) => {
  AlertIOS.alert(
      "POST Response",
      "Response Body -> " + JSON.stringify(responseData.body)
  )
}).done();
       this.props.navigation.navigate("Home")
};

Solution – 3

I also encountered this problem before. I solved it by adding this as a parameter in fetch.

header: {
  'Content-Type': 'application/json'
}

If it doesn’t work, it’s more likely an internal server error in the web service. Cheers.

Solution – 4

I found this issue the upload the images on amazon S3 and image size is large. I upload the image on lower resolution and it’s working fine for me.

Solution – 5

This Means you are getting Html response from the server probably a 404 or 500 error. Instead of response.json() use response.text() you will get the html in text.

fetch("http:/example.com", {method: "POST",
  body: JSON.stringify(
    {
      uname: uname,
      password: password      
    }
  )
})
.then((response) => response.text())
.then((responseData) => {
  AlertIOS.alert(
      "POST Response",
      "Response Body -> " + responseData
  )
}).done();
       this.props.navigation.navigate("Home")
   };

Solution – 6

this is likely when you receive html tag format from the server not the json check out the server encoding the data into proper json format you can check response by response.text() if it works than you are receiving text format.

Solution – 7

I fixed this problem my changing the multiline URLs in template literals to single-line URLs.

I had this problem on iOS, but not Android. The “same” code according to version control, and state according to testing procedures, led to this error on the iOS device emulator but not the Android device emulator.

Apple and Windows use different line endings, which is important considering template literals allow multiline strings.

// failed in iOS
fetch(`https://<API-NAME>/
?param1=${param1}
&param2=${param2}`);

// consistently works
fetch(`https://<API-NAME>/?param1=${param1}&param2=${param2}`);

Solution – 8

I am pretty sure all these answers are correct. From what I have seen, if you have properly set the request header with:

headers:{
    'Accept': 'application/json',
    'Content-Type':'application/json'
}

The Accept header will tell the server what data type we are sending. Content-Type tells the client of what the response data type will be.

You most likely had to change the format of the body because the server may not be setup to handle application/json data types. In this case if you have access to your server you can add it to a config file or in .htaccess.
If you still get the error, then there is an error in the server’s json response.

If you haven’t used POSTMAN for API testing, go and grab it because it has helped me lots with debugging API’s.

Solution – 9

In my case, I was using Infinity Free WebHosting for my API design and tests and apparently they dont allow exposure of API endpoints if you are using their free account.

That error means you are getting HTML code sent back to you and you have to do a console.log(data_response) to see the actual error. It is much easier if you are using Axios

Error that i was getting:

<html><body><script type="text/javascript" src="/aes.js" ></script><script>function toNumbers(d){var e=[];d.replace(/(..)/g,function(d){e.push(parseInt(d,16))});return e}function toHex(){for(var d=[],d=1==arguments.length&&arguments[0].constructor==Array?arguments[0]:arguments,e="",f=0;f<d.length;f++)e+=(16>d[f]?"0":"")+d[f].toString(16);return e.toLowerCase()}var a=toNumbers("f655ba9d09a112d4968c63579db590b4"),b=toNumbers("98344c2eee86c3994890592585b49f80"),c=toNumbers("c353693e65094689705f1b8cec0deb51");document.cookie="__test="+toHex(slowAES.decrypt(c,2,a,b))+"; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/"; location.href="";</script><noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript></body></html>

Solution:

Try another different Shared Hosting service provider.

Solution – 10

in my case the API website is protected by username and password, it is called basic auth.

so when i logged in from browser to the website and posted the same fetch url, it gave me the json response i needed, but when i logged in from another browser where i’m not authenticated it returned the html not authorized page.

so the answer might be a combination of both, missing headers & need for adding password and username of website in the request.

if you don’t know how to add a basic auth:

  1. enter username and password here, it will be automatically generated, you can use another website to create
    it(https://www.blitter.se/utils/basic-authentication-header-generator/)

  2. add this to your requests (customize with your own basic auth)

    headers: {
    ‘Authorization’: ‘Basic ZGV2VGVhbTpmc2xoZ2dpQHRh’
    }

VOILA.

Solution – 11

Non of the Above mentioned answers worked for me.Infact When I was fetching the api it was done correctly like

      fetch('https://reactnative.dev/movies.json')
        .then((response) => response.json())
        .then((json) => {
          console.log(json.movies);
          
        })
        .catch((error) => {
          console.error(error);
        });

but the problem was that when I tried to add the one more string in fetch i got an error like this was the code

   const fetchCities = (text) => {
        setCity(text)
        fetch('https://reactnative.dev/movies.json'+text)
        .then((response) => response.json())
        .then((json) => {
          console.log(json.movies);
          
        })
        .catch((error) => {
          console.error(error);
        });
    }

Actually I wanted to make a searchable component so I added the following chracters to remove the error so that it can combine a string to filter the data as it is searched.

?query=

in fetch statement like this

   const fetchCities = (text) => {
        setCity(text)
        fetch('https://reactnative.dev/movies.json?query=')
        .then((response) => response.json())
        .then((json) => {
          console.log(json.movies);
          
        })
        .catch((error) => {
          console.error(error);
        });
    }

The complete code that will show the filtering effect on console as you will search for a value is given below

import { text } from '@fortawesome/fontawesome-svg-core';
import React, { Component, Fragment, useState, useEffect } from 'react';
import { FlatList,SafeAreaView, StyleSheet, ScrollView, View, Text, StatusBar, Button, Image, TextInput } from 'react-native';
import BRAND_DRUG_UNIQUE from '../BRAND_DRUG_UNIQUE.json';



const Search = () => {
    const [city, setCity] = useState("")
    const [cities, setCities] = useState([])
    const fetchCities = (text) => {
        setCity(text)
        fetch('https://reactnative.dev/movies.json?query='+text)
        .then((response) => response.json())
        .then((json) => {
          console.log(json.movies);
          
        })
        .catch((error) => {
          console.error(error);
        });
    }
    useEffect(()=>{
        
        // console.log("filteredData==> ",city);
    })
    return (
        <View style={{
            position: "relative", zIndex: 1000, borderWidth: 1, borderColor: "grey", shadowColor: "#000", marginBottom: 10,
            shadowOffset: {
                width: 0,
                height: 12,
            },
            shadowOpacity: 0.58,
            shadowRadius: 16.00,

            elevation: 24,
        }}>
            <View>
                <Text>
                    It is the search component
                </Text>
                <TextInput
                    placeholder="Search here if you want"
                    style={{ color: "#00aaff" }}
                    value={city}
                    onChangeText={(text) => fetchCities(text)}
                />
            </View>
        </View>
    );
}
export default Search;

Hope it helped.Thanks.

Solution – 12

I was facing same issue, after spending hours, I came to figure out that there was a SPACE in my URL. like below

let url = "https://qinvite.vizzwebsolutions.com/api/edit_category "

So I removed SPACE from end and it got working.

Solution – 13

I guess some url misspell may cause that error.

I faced that issue working with graphql requests. In my case the issue was in request url. There was https://my.domain//graphql with double /

And another case I came across was server responded with 502 error and that caused the error.

Solution – 14

I think you can’t get response through response.json(). Because there is something like ‘<‘ in your response that cannot be converted to json.
Try with response.text()

Solution – 15

In my case I was giving extra forward slash in the end point like I have a base URL https://forexample-api.herokuapp.com/ and in the components my fetch URL was ${link.baseUrl}/api/auth/login i.e. https://forexample-api.herokuapp.com//api/auth/login

Notice that there were 2 forward slashes before api/auth…
Removing this extra forward slash solved my problem.

Solution – 16

fetch("http:/example.com", {method: "POST",
  body: "uname=value1&password=value2" // <-- Post parameters        
})
.then((responseData) => {
  AlertIOS.alert(
      "POST Response",
      "Response Body -> " + JSON.stringify(responseData.body)
  )
}).done();
       this.props.navigation.navigate("Home")
};

помогите разобраться, при оформлении заказа появляется вот такое ругательство:

SyntaxError: JSON Parse error: Unrecognized token ‘<‘ OK Notice: Undefined index: products in /var/www/u0522611/data/www/ххх/catalog/controller/extension/module/notificationTelegram.php on line 105Notice: Undefined index: products in /var/www/u0522611/data/www/ххх/catalog/controller/extension/module/notificationTelegram.php on line 105Notice: Undefined index: products in /var/www/u0522611/data/www/ххх/catalog/controller/extension/module/notificationTelegram.php on line 105{«redirect»:»http://ххх/index.php?route=checkout/success»}

код:

<?php
class ControllerExtensionModuleNotificationTelegram extends Controller {

        
    public function sendOrderAlert(&$route, &$data, &$output) {

        $order_id = $data[0];
        $this->load->model(‘checkout/order’);
        $order_info = $this->model_checkout_order->getOrder($order_id);

        $this->load->model(‘setting/setting’);
        $setting = $this->model_setting_setting->getSetting(‘module_notificationTelegram’);

        if (isset($setting[‘module_notificationTelegram_order_alert’])) {

            
            $this->load->model(‘account/order’);
            if (count($this->model_account_order->getOrderHistories($order_id)) <= 1) {
                $message = $this->replaceMessage($setting[‘module_notificationTelegram_meassage’],$order_info);
//                  $message .= $this->buldArray($order_info);

                $this->sendMessagetoTelegam($message);

                if (strpos(strtolower($setting[‘module_notificationTelegram_meassage’]), ‘{products}’) !== false) {
                    $order_products = $this->model_checkout_order->getOrderProducts($order_id);
                    $products = $this->bulidProducts($order_products);
                    $this->sendMessagetoTelegam($products);

                }
            }

            
        }

        
    }

    
    public function sendAccountAlert(&$route, &$data, &$output) {
        $this->load->model(‘setting/setting’);
        $setting = $this->model_setting_setting->getSetting(‘module_notificationTelegram’);
        if (isset($setting[‘module_notificationTelegram_customer_alert’])) {

            $message = $this->replaceMessage($setting[‘module_notificationTelegram_new_account_meassage’],$data[0]);
            $this->sendMessagetoTelegam( $message);

            
        }
    }

    
    public function sendReturnProductAlert(&$data,&$output) {
        $this->load->model(‘setting/setting’);
        $setting = $this->model_setting_setting->getSetting(‘module_notificationTelegram’);
        if (isset($setting[‘module_notificationTelegram_return_alert’])) {

            
            $message = «Return request n «;
            $this->sendMessagetoTelegam( $message);
        }
    }

    
    
    //Send  message To notificationTelegram
    public function sendMessagetoTelegam($msg) {

        
        $this->load->model(‘setting/setting’);
        $setting = $this->model_setting_setting->getSetting(‘module_notificationTelegram’);

        
        //print_r($setting);
        $botToken = $setting[‘module_notificationTelegram_boot_token’];
        $website = «https://api.telegram.org/bot» . $botToken;
        $chatIds = $setting[‘module_notificationTelegram_chat_ids’];  //Receiver Chat Id

        
        if (is_array($chatIds)) {
            foreach ($chatIds as $val) {
                $this->initMessage($botToken, $val, $msg);
            }
        } else {
            $this->initMessage($botToken, $chatIds, $msg);
        }
    }
    private function initMessage($botToken, $chatID, $msg) {

        
        $website = «https://api.telegram.org/bot» . $botToken;

        
        $params = [
            ‘chat_id’ => $chatID,
            ‘text’ => $msg,
        ];
        $ch = curl_init($website . ‘/sendMessage’);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, ($params));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $result = curl_exec($ch);
        curl_close($ch);            
    }

    
    public function buldArray($arr) {
        if (is_array($arr)) {
            $dataAttributes = array_map(function ($value, $key) {
                return @»$key —> $value  n»;
            }, array_values($arr), array_keys($arr));

            
            return $dataAttributes = implode(‘ ‘, $dataAttributes);
        }
    }

    
    public function replaceMessage($string,$arr) {
        return   $str = preg_replace_callback(‘/{(w+)}/’, function($match) use($arr) {
            return $arr[$match[1]];
        }, $string );

        
    }

    
    protected function  bulidProducts($products){

        $pr = array();

        foreach ($products as $product){
            $pr[] = «Name : $product[name]  n    Price: $product[price] n qty : $product[quantity] «;
        }

        return implode(«——- n»,$pr);

        
    }

        
}

Write bug, find bug

If you write WordPress plugins and make AJAX requests, you may be familiar the dreaded Javascript error: SyntaxError: JSON Parse Error: Unrecognized token '>'

SyntaxError: JSON Parse Error: Unrecognized token '<'

Why? Why!?!

What it means is that the response your code expected is screwed up because a plugin barfed PHP warnings into the admin-ajax.php ventilation system.

When WP_DEBUG is on, admin-ajax.php responses can include junk HTML output from PHP warnings, like:

<br />
<b>Notice</b>:  Undefined offset: 0 in
<b>/wp-content/plugins/im-gonna-break-ur-ajax.php</b> on line
<b>666</b><br />

The fix? Catch exceptions, then exceed expectations

The way to fix this is to wrap the jQuery.parseJSON() function in try/catch. That will make sure that the code doesn’t fully blow up.

try {
  jQuery.parseJSON( response );
} catch( exception ) {
  console.log( exception );
}

That will prevent your code from breaking, but it won’t make your code work.

The cause of the code breaking is the junk HTML at the beginning on the AJAX response. So, what we want to do is:

  1. Check for a valid JSON response
  2. If the JSON is invalid, strips all characters until finding a JSON-style opening of {".
  3. Check the newly stripped string to see if that is valid JSON
  4. If valid, return the JSON. If not, return an error message.

Here’s the code to achieve that:

Let me know what you think, and please fork the Gist if you have any improvements!

Понравилась статья? Поделить с друзьями:
  • Ошибка kernel event tracking код 2
  • Ошибка json exception parse error 101
  • Ошибка kernel power код 137
  • Ошибка kernel data inpage error это что такое
  • Ошибка json error syntax error 4