VicDid
VicDid

Reputation: 175

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 bk: 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 jsonContent['bk:ParentField'] 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:'?

Upvotes: 0

Views: 935

Answers (2)

Chris Seymour
Chris Seymour

Reputation: 85785

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, ''));

Or provide an encoding:

fs = require('fs');

var contents = fs.readFileSync("test.json", "utf-8");
var data = JSON.parse(contents.replace(/bk:/g, ''));

Both methods yield the expected result and allow properties to accessed with the . operator:

console.log(data.ParentField.Field);

The replace is not strictly required if you don't mind accessing properties like so:

var data = JSON.parse(fs.readFileSync("test.json", "utf-8"));
console.log(data["bk:ParentField"]["bk:Field"])

Upvotes: 4

Christian Zosel
Christian Zosel

Reputation: 1424

It seems that your problem is not the : in the object keys, but the fact that there are no enclosing {} in your JSON string, which makes it invalid. See this example:

var parsed = JSON.parse(`{
  "bk:ParentField": {
    "bk:Field": "Value",
    "bk:Field2": "Value2"
  }
}`)
console.log(parsed['bk:ParentField'])

Upvotes: 0

Related Questions