admin管理员组

文章数量:1357091

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 ment 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 "@/ponents/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 unment 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.

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 ment 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 "@/ponents/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 unment 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.

Share Improve this question edited Oct 13, 2020 at 4:34 L.fole asked Oct 13, 2020 at 3:25 L.foleL.fole 8074 gold badges13 silver badges19 bronze badges 4
  • 1 this has nothing to do with Nextjs! JSON.parse({"data":{"countries":[{"name":"Canada"}]}}) is wrong, because its already a valid JSON, instead of a string. Do JSON.stringify({"data":{"countries":[{"name":"Canada"}]}}), thats it – boop_the_snoot Commented Oct 13, 2020 at 3:27
  • @boop_the_snoot, I'm getting json in the form of string from getStaticProps() and trying to parse in main function. As for the example, you can assume, var countriesString = JSON.stringify({"data":{"countries":[{"name":"Canada"}]}}) in getStaticProps() and variable countriesString passed via props. – L.fole Commented Oct 13, 2020 at 3:32
  • if thats the case, follow the answer by @anway, and switch variables/values wherever necessary – boop_the_snoot Commented Oct 13, 2020 at 3:38
  • @L.fole JSON.parse is to convert a string to a valid JavaScript object. However, what you are right now doing is already inputting a valid JavaScript object into the JSON.parse, which is not necessary. You can delete that code, because what you are trying to do is parsing an already parsed object. – Anvay Commented Oct 13, 2020 at 12:18
Add a ment  | 

2 Answers 2

Reset to default 1

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.

my simple solution is:

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

本文标签: javascriptJSON parse in NextjsStack Overflow