-1

My JSON value has a value with hyphen like database-name.

I wanted to replace the value of the database-name using below code

    result.databases.database-name = 'ArangoDB';

But it is showing error, How to call the JSON value when the value is having hyphen

Here is a code

const fs = require("fs");
const xml2js = require('xml2js');

fs.readFile("databases.xml", "utf-8", (err, data) => {
    if (err) {
        throw err;
    }

    xml2js.parseString(data, (err, result) => {
        if (err) {
            throw err;
        }

        result.databases.database-name = 'ArangoDB';

       
        const builder = new xml2js.Builder();
        const xml = builder.buildObject(result);

        fs.writeFile('new-databases.xml', xml, (err) => {
            if (err) {
                throw err;
            }

            console.log(`Updated XML is written to a new file.`);
        });

    });
});
Andy
  • 61,948
  • 13
  • 68
  • 95

2 Answers2

1

You can use this syntax to access object members with a string as the key

result.databases["database-name"] = 'ArangoDB';

Here is the reference

Sadra M.
  • 1,304
  • 1
  • 17
  • 28
0

Try to do like this:

result.databases["database-name"]

That's the way to access properties when you have a hyphen in their key names.

leonardomdr
  • 169
  • 6
  • It is working fine and not showing any error now. – Alwaysdoubt Jul 17 '22 at 09:56
  • But the value is not replaced in the xml file, is there any other way? – Alwaysdoubt Jul 17 '22 at 09:57
  • I've done a test locally here and it worked. Are you sure you're changing the correct property at the correct place? Try doing a `console.log(result.databases['database-name']);` before doing the change to `ArangoDB` and check if you're getting the current database name from the file. – leonardomdr Jul 17 '22 at 10:12
  • Thanks - the value is correct in console.log. But not getting updated in xml. Let me check my code for saving xml – Alwaysdoubt Jul 17 '22 at 10:25