-2

I've come across something I don't entirely understand and cannot solve however I try.

Say I have an object:

const jsonExample = {
    textToReplace: 'My text',
    arrayToReplace: 'My array: ${arrayParam}',
};

And I need to stringify this object in order to replace the arrayParam:

const myArray = ['foo', 'bar'];
const stringifiedJson = JSON.stringify(jsonExample).replace('${arrayParam}', JSON.stringify(myArray));

And then I need to parse it back to an object, and get my array back:

const newJson = JSON.parse(stringifiedJson);

But I get a SyntaxError at the beginning of the stringified array. Is there something I'm missing?

I know it's a rather convoluted way of doing things, but in my real problem I have an iterative replacing method which, up until now, only dealt with strings, but I need it to also replace arrays.

Thanks!

Edit: the error is: SyntaxError: Unexpected token f in JSON at position 57

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Mario MG
  • 364
  • 2
  • 13
  • May you please share the error as well – RynohRR Aug 25 '20 at 10:49
  • 2
    "Say I have a JSON" — that is an **object**, not JSON. JSON is when you get from `JSON.stringify`. See http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/ – Quentin Aug 25 '20 at 10:50
  • 1
    Doing a find & replace on a string of JSON sounds like an excellent way to break it. Loop over the properties of the object and replace the values one at a time instead. – Quentin Aug 25 '20 at 10:52
  • I would do it some other way, but I do need a specific method, which usually takes strings and does the replacing, to take this object as well (and I cannot modify said method) – Mario MG Aug 25 '20 at 10:56

1 Answers1

1

When you use .replace() you're adding the string [\"foo\",\"bar\"] to your stringified object:

"{\"textToReplace\":\"My text\",\"arrayToReplace\":\"My array: [\"foo\",\"bar\"]\"}"

Above the \"My array: [\" is interpreted as the value for "arrayToReplace" when parsed. So, the following f is interpreted as token and not part of your string value, resulting in your error.

You can instead use the replacer function for JSON.stringify() to parse your string first and then the entire object.

See example below:

const jsonExample = {
    textToReplace: 'My text',
    arrayToReplace: 'My array: ${arrayParam}',
};

const myArray = ['foo', 'bar'];
const stringifiedJson = JSON.stringify(jsonExample, (key, val) =>{
  return typeof val === "string"
    ? val.replace('${arrayParam}', JSON.stringify(myArray))
    : val;
});

const newJson = JSON.parse(stringifiedJson);
console.log(newJson);
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64