L.fole
L.fole

Reputation: 807

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.

Upvotes: 3

Views: 21402

Answers (2)

Sanjay Sikdar
Sanjay Sikdar

Reputation: 562

my simple solution is:

export const parseJson = (data) => {
    let item;
    if (typeof window !== 'undefined') {
        // Perform localStorage action
        item = JSON.parse(data)
    }
    return item
};

Upvotes: 0

Anvay
Anvay

Reputation: 363

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.

Upvotes: 1

Related Questions