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.