简体   繁体   中英

Parse a stringified JSON containing a stringified array

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM