Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON parse in Nextjs

I'm bit new to Javascript. This seems silly question. Im trying to parse JSON in the Nextjs Main function. When I try to parse JSON in main function before return statement, it shows 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

On Question Details

The earlier comment indeed solves the question earlier asked. Thank you @boop_the_snoot and @Anvay .However, that's not exactly the issue I'm trying to reproduce the error.

I've nextjs route [forecastCategory]/[xquote]/[forecastid].js with 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) => {
  // HERE JSON STRING DIRECT ENTRY.
  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 above code on the route /daily-forecast/1-quote/DFP4362832 produce the following:

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

However, when I uncomment var myStocks = JSON.parse(stocksString) it produce the earlier JSON parse error SyntaxError: Unexpected token o in JSON at position 1 I'm still not able to figure out the JSON parsing issue.

like image 299
L.fole Avatar asked Feb 23 '26 16:02

L.fole


2 Answers

I see that you are using JSON.parse(), which is correct. However, JSON.parse takes in only a string, so to solve that you can change your code to this:

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

Remember to escape the quotes! It is not considered valid JSON to use single quotes for the text.

like image 184
Anvay Avatar answered Feb 26 '26 06:02

Anvay


my simple solution is:

export const parseJson = (data) => {
    let item;
    if (typeof window !== 'undefined') {
        // Perform localStorage action
        item = JSON.parse(data)
    }
    return item
};
like image 29
Sanjay Sikdar Avatar answered Feb 26 '26 06:02

Sanjay Sikdar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!