Exploring JSON parsing capabilities in Next.js

As a newcomer to Javascript, I have a query that may seem silly. I am attempting to parse JSON in the main function of Nextjs. However, when I try to parse JSON in the main function before the return statement, I encounter the error

SyntaxError: Unexpected token o in JSON at position 1

export default function Home() {
    const countries = JSON.parse({"data":{"countries":[{"name":"Canada"}]})
    return (
        <pre>{JSON.stringify(countries)}</pre>
    )
}

UPDATE

Regarding Question Details

The previous comment did provide a solution to the earlier question. Thank you to @boop_the_snoot and @Anvay. However, the issue I am trying to address is not exactly the same as the one resolved.

I have a Nextjs route

[forecastCategory]/[xquote]/[forecastid].js
with the following code:

import {pathsData} from "@/components/Data"


export default function ForecastID({ stocksString}) {
    //var myStocks = JSON.parse(stocksString)
    return (
      <>
      
      <pre>{stocksString}</pre>
      
    </>
  );
}


export const getStaticProps = async (ctx) => {
  // JSON STRING DIRECTLY ENTERED HERE.
  var stocksDataTemp = {
    "daily-forecast--1": {
      "DFP4362832": [
        "SJ78449",
        99,
        21,
        99,
        "View",
        [
          {
            "name": "STOCK111",
            "LTP": 164.35,
            "BUY": 170,
            "SELL": 177,
            "GAIN": 3.95
          }
        ]
      ],
      "DFP1329702": [
        "SJ59264",
        98,
        21,
        96,
        "View",
        [
          {
            "name": "STOCK112",
            "LTP": 475.1,
            "BUY": 484,
            "SELL": 497,
            "GAIN": 2.62
          }
        ]
      ]
    },
    "daily-forecast--2": {
      "DFP8899451": [
        "SJ49453",
        99,
        21,
        98,
        "View",
        [
          {
            "name": "STOCK113",
            "LTP": 1787.25,
            "BUY": 1894,
            "SELL": 1935,
            "GAIN": 2.12
          },
          {
            "name": "STOCK114",
            "LTP": 467.3,
            "BUY": 481,
            "SELL": 493,
            "GAIN": 2.43
          }
        ]
      ],
      "DFP9681539": [
        "SJ54067",
        97,
        25,
        91,
        "View",
        [
          {
            "name": "STOCK115",
            "LTP": 194.5,
            "BUY": 201,
            "SELL": 211,
            "GAIN": 4.74
          },
          {
            "name": "STOCK116",
            "LTP": 1461.15,
            "BUY": 1563,
            "SELL": 1612,
            "GAIN": 3.04
          }
        ]
      ]
    }
  }

  const xquote = ctx.params.xquote;
  console.log("xquote:", xquote)
  const quoteCount = xquote.split("-", 1)[0];
  console.log("quoteCount:", quoteCount)
  const forecastCategorySlug = ctx.params.forecastCategory;
  console.log("forecastCategorySlug:", forecastCategorySlug)
  const forecastid = ctx.params.forecastid; 
  console.log("forecastid:", forecastid)

  var stocksPageData = stocksDataTemp[forecastCategorySlug + "--" + quoteCount][forecastid];
  console.log("stocksString:", stocksString)
  var stocksPageDataString = JSON.stringify(stocksPageData);
  var stocksString = JSON.stringify(stocksPageData[5])
  console.log("stocksString:", stocksString)
  //var countriesString = JSON.stringify({"data":{"countries":[{"name":"Canada"}]})

  return {
    props: {
      stocksString,
    },
  };
};

export const getStaticPaths = async (ctx) => {
...
}

The code on the route

/daily-forecast/1-quote/DFP4362832
produces the following output:

[{"name":"STOCK111","LTP":164.35,"BUY":170,"SELL":177,"GAIN":3.95}]

However, when I uncomment

var myStocks = JSON.parse(stocksString)
, it results in the earlier JSON parse error
SyntaxError: Unexpected token o in JSON at position 1
. I am still struggling to pinpoint the issue with JSON parsing.

Answer №1

It appears that you are utilizing the JSON.parse() function, which is the correct approach. However, it's important to note that JSON.parse only accepts a string as input. To address this issue, you can simply modify your code as follows:

export default function HomePage() {
    const countries = JSON.parse("{\"data\":{\"countries\":[{\"name":"Canada\"}]}}")
    return (
        <pre>{JSON.stringify(countries)}</pre>
    )
}

Make sure to properly escape the quotes! Remember, using single quotes within the JSON data is not considered valid.

Answer №2

Here's a straightforward fix:

const decodeJson = (json) => {
    let result;
    if (typeof window !== 'undefined') {
        // Handle localStorage operation
        result = JSON.parse(json)
    }
    return result
};

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

TailWind CSS output.css file does not include every single class available in the library

While generating a Tailwind output CSS file, I noticed that it is not generating all the expected classes. For example, Tailwind supports margins and padding up to -16, but it only generates classes from 1 to 4. Anything beyond 4 does not work. Here is a ...

Embedding HTML Tags within an array element

The task at hand involves adding an HTML element from Array Value to the Document Object Model template: { 0: { h1: '<h1>Hi</h1>' }, 1: { h2: '<h2>Hi</h2>' }, 2: { h3: &a ...

Utilizing PHP for Interactive JavaScript Modals

Encountering an issue with my JavaScript. The modal initially functions correctly, but upon clicking it for the second time, two modals appear - one from the previous click and another new one. The stacking of modals continues each time the button is cli ...

ExpressJS, defining routes, locating controllers, and documenting APIs

Utilizing expressJS 4.X and nodeJS 6.x In the past, I was defining my routes in this manner : /** * @api {get} /users/:userId Get a user * @apiName GetUser * @apiGroup User * * @apiParam {Integer} userId Users unique ID. * * @apiSuccess (Success 2 ...

Tips for creating a high-performing algorithm to locate a specific word within a JSON file

I am in the process of creating a word game that involves users typing letters on a board to form meaningful words. If the typed word matches any word in a JSON file, the user earns a point. I have successfully implemented the basic functionalities of the ...

Sharing the current state with unspecified child elements

As someone new to React, I'm having trouble figuring out how to pass hover state down through components. I'm working with Next.js and styled-jsx. Back in the day with plain CSS, it was easy to change the text color of an element when its parent ...

Is there a way to display errors during jQuery validation?

Is there a specific function that can provide all error messages generated during form validation? I attempted to use the defaultshowerrors() function, but it only shows errors for the current element being validated. Is there a way to retrieve all error ...

Sending form data using Ajax in codeigniter

I am encountering an error while attempting to submit a form using ajax in codeIgniter. Below is the view code that I have: <div class="form-group input-control"> <p id="error1" style="display: none; color: green"><b>Registered Succ ...

Strategies for breaking apart a large, monolithic Node.js JavaScript application

My node.js server application is expanding, and I am looking to split it into multiple files. Below is a snippet of the current monolithic server.js file: var express = require('express'); var app = express(); // other initialization code etc / ...

How come attempting to read a nonexistent document from Firestore results in an uncaught promise?

I've been struggling to read and display data from Firestore, but I keep seeing error messages in the console. Encountered (in promise) a TypeError: Unable to read properties of undefined (reading 'ex') Encountered (in promise) a TypeError ...

Tips on integrating googleapis with apps script

My goal: I am trying to implement the Google Calendar's API acl.list() in a Google Script using the UrlFetchApp.fetch() function. Issue: The Google script itself has an OAuth token when it runs. However, the problem arises when the UrlFetchApp.fetc ...

Ensuring grid columns are equal for varying text sizes

I am looking to achieve equal width and spacing for columns without using the width, min-width, max-width properties. Can anyone help me accomplish this using flex or any other method? https://i.sstatic.net/xo56M.png .d-flex { display: flex; } .d-fl ...

Is it feasible to retrieve a query parameter from a dynamic page in next.js?

When a user directly accesses my next.js site with query parameters, I noticed that the page does not recognize certain additional query parameters when it is dynamic and has internal "params." Despite using useRouter, the actual query parameter is not bei ...

The iisnode module is having difficulty in initializing the node.exe process

My iisnode module is having trouble starting the node.exe process. I need to ensure that the node.exe executable is located where it should be according to the system.webServer/iisnode/@nodeProcessCommandLine element in the web.config file. Typically, node ...

What is the best way to mix up the middle letters within certain positions of a word?

Here is what I have managed to achieve so far: mounted() { const randomVariants = [...Array(3)].map(() => this.baseWord .split('') .sort(() => 0.5 - Math.random()) .join('') ) const variantsWithoutIniti ...

Calculate the cumulative values in ng-repeat using AngularJS

I used ng-repeat to iterate through a JSON array. I calculated the number of nights by utilizing the dayDiff() function. Now, I need to find the total number of nights for all invoices. My project is built with AngularJS. Is there a way to retrieve the to ...

Strange HTML antics

On my website, I encountered an issue when trying to register without entering any information into the required fields. The errors were correctly displayed in this screenshot: https://i.sstatic.net/wrxjt.png However, after inserting random characters in ...

AngularJS encountered an error: [$injector:modulerr] problem occurred during code execution

Hey there! I've been trying to set up a pop-up feature in Angular, but unfortunately, I keep encountering an error: Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.4.9/$injector/modulerr?p0=PopupDemo&p1=Error%…ogleapis.com%2Fa ...

Issue with Node.js Express function not returning the variable fetched from fs.readFile operation

I am facing an issue with a function in my Node.js application that uses Express. function getMetaInfo(id){ var directory = 'files/' + id; var totalCount = 0; fs.readFile(__dirname + '/' + directory + '/myfile.json&ap ...

What is the best way to rate a particular image?

while ($row = mysqli_fetch_array($result)) { echo ""; echo "<div id='img_div'>"; echo "<i class='fas fa-times'></i>"; echo "<img class='photoDeGallery' s ...