1

I have this JSON file: (EDITED)

{
  "user": {
    "S-1-5-21-2659826518-2396530539-1407762326-1001": {
      "username":"xyz",
      "password":"xyz@123",
      "email":"xyz@xyz.com",
      "uid": 1100
    },
    "S-1-5-21-2659826518-2396530539-1407762326-1002": {
      "username":"abc",
      "password":"abc@456",
      "email":"abc@abc.de",
      "uid": 2222
    }
  }
}

(the JSON file is valid)

and I need to get the values out of it. But when I try to parse the JSON file an error appears:

console.log(jsonContent.S-1-5-21-2659826518-2396530539-1407762326-1001.username);
                                                                  ^^^^^
SyntaxError: Invalid or unexpected token

also, the username is underlined red from my syntax highlighter. (so there is something wrong)

So I searched the internet and found nothing about it.

Here is my code:

const fs = require('fs');
const filename = "C:/Users/Jonas/Documents/Visual_Studio_Code/Node.js/json.json"

contents = fs.readFileSync(filename);
jsonContent = JSON.parse(contents);
console.log(jsonContent.S-1-5-21-2659826518-2396530539-1407762326-1001.username);

For the case I need it, I cant edit the problematic part S-1-5-21-2659826518-2396530539-1407762326-1001.

I also tried to set it like this: console.log(jsonContent."S-1-5-21-2659826518-2396530539-1407762326-1001".username); but that's ever wronger.

For any more information please ask.

programmer
  • 27
  • 1
  • 6

1 Answers1

0

You need to use the square bracket notation because the property name has hyphens in it which JavaScipt interprets as the minus (-) operator:

jsonContent['S-1-5-21-2659826518-2396530539-1407762326-1001'].username;

Snippet:

const jsonContent = {
  "S-1-5-21-2659826518-2396530539-1407762326-1001": {
    "username":"xyz",
    "password":"xyz@123",
    "email":"xyz@xyz.com",
    "uid": 1100
  },
  "S-1-5-21-2659826518-2396530539-1407762326-1002": {
    "username":"abc",
    "password":"abc@456",
    "email":"abc@abc.de",
    "uid": 2222
  }
}

const name = jsonContent['S-1-5-21-2659826518-2396530539-1407762326-1001'].username;

console.log(name);
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156