0

I have a query that gets data from SQL Server, and in one of the fields we are storing JSON as a varchar(max). The issue is that when I try to get the data out in my Node app and do a JSON.parse, it's not working. Here's what I've tried:

console.log(data.attr);
    // "{ firstName: 'Preston', lastName: 'Lamb' }"
JSON.parse(data.attr) 
    // Invalid expression: unexpected end of input (get this on one item)
    // invalid expression: unexpected token f in json at position 2 (and this on the other)
newJsonStr = JSON.stringify(data.attr)
    // ""{ firstName: 'Preston', lastName: 'Lamb' }""
newJson = JSON.parse(newJsonStr)
    // "{ firstName: 'Preston', lastName: 'Lamb' }"

enter image description here

None of this is really complicated stuff...it should be easy to JSON.parse and/or JSON.stringify, but it doesn't work. Any ideas at all?

pjlamb12
  • 2,300
  • 2
  • 32
  • 64

1 Answers1

1

What the other commentator meant by it's not JSON is that your keys need to be wrapped in quotes to be parsed as JSON.

JSON Spec - does the key have to be surrounded with quotes?

Community
  • 1
  • 1
chairmanmow
  • 649
  • 7
  • 20
  • 1
    Whenever I encounter a JSON error like this, I will always verify the data using JSON Lint, available: Website version: [jsonlint.com](https://jsonlint.com) NPM CLI version: [npmjs.com/package/jsonlint](https://www.npmjs.com/package/jsonlint) – Steven Stark May 04 '17 at 20:34
  • Okay, when I inserted manually into the database I forgot that. But putting double quotes around attributes and values, and even escaping them, still causes issues. Just trying to parse the response is where the `invalid expression: unexpected end of json input` error came from, and when you `JSON.stringify` it first it adds doesn't do anything. – pjlamb12 May 04 '17 at 20:38
  • 1
    @StevenStark After using JSON lint, I could see that one of those fields was missing a double quote, and so it wasn't parsing correctly. I'll have to work on the other field to make sure to add it properly to the database. Thanks! – pjlamb12 May 04 '17 at 20:47
  • @pjlamb12 Don't try to create JSON by hand. Most languages have library functions to create JSON, you should use it. – Barmar May 04 '17 at 20:49