VicDid VicDid - 1 year ago 82
Javascript Question

Removing instances of a string from a JSON file and then parsing it

I have a JSON file with a lot of content and I load it with the fs Node.js module. But when I look in the JSON file I noticed there is a string of characters attached to many of the field names that make it impossible to target in JS. It looks something like this:

"bk:ParentField": {
"bk:Field": "Value",
"bk:Field2": "Value2"

I want to remove the
part because I am unable to target the objects with them in it. My code looks like this :

var contents = fs.readFileSync("results.json");
var jsonContent = JSON.parse(JSON.stringify(contents).replace(/bk:/g, '' ));

The problem that whenever I try to target an item after running the code above, I get an error saying an undefined or if I do something like
I still get an undefined error.
Any ideas on why this would happen? Or is there a workaround to targeting the objects with the 'bk:'?

Answer Source

The function readFileSync returns a buffer if an encoding is not provided and JSON.stringify takes an Object not a string or buffer.

Just call toString() on the contents buffer before using replace() and then use JSON.parse to create a JavaScript Object:

fs = require('fs');

var contents = fs.readFileSync("test.json");
var data = JSON.parse(contents.toString().replace(/bk:/g, ''));
console.log(data.ParentField.Field);  // Value

Or provide an encoding:

fs = require('fs');

var contents = fs.readFileSync("test.json", "utf-8");
var data = JSON.parse(contents.replace(/bk:/g, ''));
console.log(data.ParentField.Field);  // Value
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download