I encountered difficulty in assigning a JSON response to a variable, both with and without using JSON.parse()

I'm in the process of creating a website that, among other things (and crucially for this particular issue), stores your current location data in a variable by fetching it from the ipinfo API (https://ipinfo.io/json)

After encountering the problem of my website initially displaying "undefined" in the location section and subsequently redirecting me to url/[object%20Object], I attempted to resolve it using JSON.parse(). However, upon implementing parse, I encountered the following error in the console log: (see below)

The JSON response can be directly utilized without saving, with no adverse effects. To view its structure, you can visit the API link provided above.

Below is the JavaScript code I have incorporated:

var location;

// invoked once the document has loaded completely
$(document).ready(function(){

    // retrieves and displays your current location data
    $.get("https://ipinfo.io/json", function(response) {

        location = JSON.parse(response);
        console.log(location);
        document.querySelector('.location').innerHTML = location.city;

    });

Here is the corresponding HTML:

<h4>You are playing from:</h4>
<div>
    <p class="location"></p>
    <p class="country"></p>
    <p class="region"></p>
</div>
<div class="row">
  <div class="column">
      <h3>Column 1</h3>
      <p id="city_a">
      </p>
  </div>
  <div class="column">
      <h3>Column 2</h3>
      <p id="city_b">
      </p>
  </div>

This error message appears in the console:

VM102:1 Uncaught SyntaxError: Unexpected token o in JSON at position 1

at JSON.parse ()
at Object.success ((index):64)
at u (VM94 jquery-3.3.1.min.js:2)
at Object.fireWith [as resolveWith] (VM94 jquery-3.3.1.min.js:2)
at k (VM94 jquery-3.3.1.min.js:2)
at XMLHttpRequest. (VM94 jquery-3.3.1.min.js:2)

Any assistance would be greatly appreciated! Thank you in advance!

Answer №1

Your response data has already been converted into a JavaScript object thanks to the Content-Type in the response header. You can simply use the response object directly:

$.get("https://ipinfo.io/json", function (response) {
  document.querySelector('.location').innerHTML = response.city;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p class="location"></p>

The error you're encountering when trying to parse the object is because JSON.parse() ends up calling object.toString(), resulting in "[object Object]":

const obj = {};

console.log(obj.toString()); // "[object Object]"
JSON.parse(obj); // Unexpected token o in JSON at position 1

The confusing redirect issue arises from the global Window.location variable. Declaring let location; triggers an error stating

"Uncaught SyntaxError: Identifier 'location' has already been declared"
. Renaming the variable fixes this problem.

let location; // Uncaught SyntaxError: Identifier 'location' has already been declared

location = "foo bar";

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Filtering a REST API response with PHP using a MySQL database

Currently, I am working on a JSON API project that involves PHP and MySQL database. So far, I have successfully implemented post and get functions. However, I am facing an issue with the filter feature. When searching for names in the database, I am only a ...

The new pop-up window appears smaller than expected in Internet Explorer

There has been a bug report regarding the course opening in a smaller popup window. The JavaScript code used to open the popup is: course_window=window.open(urlString,"", "toolbar=0,directories=0,location=0,status=0, menubar=0,fullscreen=0,scroll ...

Creating a personalized grid display

https://i.sstatic.net/tLd7X.png I've been trying to achieve the following output with my code, but so far nothing has worked. Can someone help me identify what I may be doing wrong? I'm new to this, so any guidance would be greatly appreciated. ( ...

Issue with Webpack: error message "Cannot read property 'readFile' of undefined" is causing no output files to be generated

When utilizing version webpack > 5, the configuration for my appDevMiddleware.js is as follows: const path = require('path'); const webpack = require('webpack'); const webpackDevMiddleware = require('webpack-dev-middleware' ...

Utilizing the change function in conjunction with that

My attempt at creating a simple function to implement the change function didn't go as planned:/ What I am trying to achieve: 1- When a cost checkbox is checked, assign the corresponding cost (e.g., cost1.checked ? cost1 = 10 : 0) 2- Calculate and di ...

In JavaScript, what is the best way to target the initial option element in HTML?

As a newcomer to javascript, I'm wondering how to target the first option in the HTML <option value="">Choose an image...</option> without altering the HTML itself? My thought is: memeForm.getElementById('meme-image').getElement ...

I'm having trouble getting jquery css to function properly in my situation

I am trying to implement a fallback for the use of calc() in my CSS using jQuery CSS: width: calc(100% - 90px); However, when I tried running the code below, it seems like the second css() function is not executing. I suspect that there might be an issu ...

Having trouble sharing content from my React next.js website on social media due to issues with open graph meta tags

I'm currently facing an issue with my Next.js application when trying to share content on Facebook and Twitter. I've made sure to include the necessary open graph meta tags in the document's head section and I'm using React Helmet to dy ...

Encountering a problem where a 'List<dynamic>' type is not recognized as a subtype of a 'Map<String, dynamic>' type

I am currently working on a flutter app that is meant to showcase users in a list format. While I have been successful in fetching and printing the data, displaying it presents an issue for me as I keep encountering this error message Exception has occurre ...

Is there a way to display the specific information of a flatlist item in a pop-up window?

Welcome to the HomesScreen.js! This section handles rendering the flat list elements. import { StatusBar } from 'expo-status-bar'; import { Button, Image, Modal, StyleSheet, Text, TouchableOpacity, View } from 'react-native'; import { ...

Having trouble determining why the design is not displaying correctly

I'm currently working on a calendar webpage, and everything looks perfect until I add the new JavaScript element. Suddenly, the numbers in the first row start behaving strangely. I've tried to troubleshoot but can't seem to figure out what&a ...

The custom validation process encountered an error: callback is not a valid function

Encountering an issue with a custom validator in node.js while using mongoose. The goal is to verify if a query already exists in the headerLog before attempting to insert it. Take a look at the code snippet below: var mongoose = require('mongoose& ...

Modifying the onclick function for a bootstrap glyphicon

How can I swap the .glyphicon-menu-down to glyphicon-menu-up when a user clicks on a link? Currently, it's not working as expected. Could there be an issue with my jQuery implementation? Markup <a data-toggle="collapse" data-parent="#accordion" h ...

Passing a Typescript object as a parameter in a function call

modifications: { babelSetup?: TransformationModifier<babel.Configuration>, } = {} While examining some code in a React project, I came across the above snippet that is passed as an argument to a function. As far as I can tell, the modifications p ...

How can the front design of Material-UI's Card header be customized?

Currently, I am facing an issue with the Material-UI card header as the background color is affecting the readability of the default font. My aim is to use the typography prop h4 for the header, but I am struggling to achieve this. https://i.stack.imgur.c ...

Exploring the deep nested structure of an object array JSON file through mapping

I am currently working on mapping a nested JSON file, but I am encountering some difficulties. When I log the data in the console, it returns as an 'object' and I am unable to go further than that. (Please note that I am still learning JavaScript ...

Tips for concealing subsequent pages and displaying pagination in jQuery ajax response

Is there a way to display pagination based on a limiter in an ajax response? For example, if the limiter is set to 5, only show 10 page links and hide the rest. 1 2 3 4 5 6 7 8 9 10 .. next 11 12 13 14 15.. next I attempted to count the li elements in ...

Can a javascript code for "Infinite Scroll" be created to manage the back button?

Head over to this website: Experiment with the infinite scroll feature. You may notice that when you click a link and then press "back", there are some glitches. Therefore, I am considering developing my own version of an Infinite Scroll functionality. ...

Is it possible to modify the sub/child divs within a draggable parent div and assign them a different class?

Greetings, after being a long-time reader, I have finally decided to post for the first time. In the process of creating a webpage with jQuery drag and drop divs, I am curious about how to change the class of a child div within a draggable div once it is d ...

Transform a JSON string into an object by analyzing the JSON string's format

I am facing a challenge with converting JSON data from a third party API call into the appropriate objects, as the data consists of an array of various event objects. Here is a snippet of the JSON response: [{ "id": 1, "globalID": 1, "time": ...