0

I've got a JSON object that's being submitted to a AWS Lambda NodeJS function. This JSON object has an apostrophe in one of the fields that I need to escape before it's being inserted into a MySQL database.

The object needs to stay intact as it's being stored as a JSON object in the database. I've looked at string replace functions but those won't work since this is a JSON object natively.

I'm sure there is a simple answer here, I'm just very new to NodeJS and haven't found a way after searching around for a few hours. Thanks in advance!

The field I need to update is 2.1 below:

Example of the BAD JSON Object:

{
  "field1": "ABCD1234DEFG4567",
  "field2": "FBI",
  "fieldgroup": {
    "1.1": "ABCD",
    "1.2": 20170721,
    "1.3": "ABCD",
    "2.1": "L'astName, FirstName M"
  }
}

Example of the FINAL JSON object:

{
  "field1": "ABCD1234DEFG4567",
  "field2": "FBI",
  "fieldgroup": {
    "1.1": "ABCD",
    "1.2": 20170721,
    "1.3": "ABCD",
    "2.1": "L''astName, FirstName M"
  }
}
2
  • You could convert the values to utf-8 and store it that way. npmjs.com/package/utf8 Commented Jul 21, 2017 at 19:58
  • 1
    To be pedantic, there is no 'JSON object', it's either JSON (unparsed -- a string) or a JS value (parsed -- an object, array, string, etc.). Commented Jul 21, 2017 at 20:38

2 Answers 2

2

const o = {
    "field1": "ABCD1234DEFG4567",
    "field2": "FBI",
    "fieldgroup": {
        "1.1": "ABCD",
        "1.2": 20170721,
        "1.3": "ABCD",
        "2.1": "L'astName, FirstName M"
      }      
   };
   
const preparedObject = prepare(o);
console.log(JSON.stringify(preparedObject, null, 4));

function prepare(o) {
  const replacedStrings = Object.keys(o)
    .filter(key => typeof o[key] === "string")
    .reduce((accu, key) => ({ ...accu, [key]: o[key].replace("'", "''") }), {});
  const preparedChildren = Object.keys(o)
    .filter(key => typeof o[key] === "object")
    .reduce((accu, key) => ({ ...accu, [key]: prepare(o[key]) }), {});
  return { ...o, ...replacedStrings, ...preparedChildren };
}

Sign up to request clarification or add additional context in comments.

Comments

2

If you're getting the value as JSON, do a string replace on the JSON and return back as an Object, this should work.

let escapeSingleQuotes = json => {
  return JSON.parse(json.replace(/'/, "''"))
}

If you want to remove the single quotes from a JS Object, its the same as above but, convert to a string first then go back to an object

let escapeSingleQuotes = obj => {
  return JSON.parse(JSON.stringify(obj).replace(/'/, "''"))
}

1 Comment

Please use const for functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.