Home > Blockchain >  How do I handle newlines in JSON keys
How do I handle newlines in JSON keys

Time:05-28

I have some poorly formatted JSON which has newlines in the keys.

The raw JSON looks like:

{
  "Some\\nKey": "Some\\nvalue",
  "Some nice key": "Some nice value"
}

I have a matching data source which, for keys without newlines works very happily to convert "Some nice key" into "Some nice value". However, when the matching data source contains newlines, the lookup fails. My code looks something like:

const translations = JSON.parse(fileContents);
var value = translations[key];
if (value == null) {
  const fixedKey = JSON.stringify(key).replace(/\\n/g, "\\\\n");
  value = translations[fixedKey];
  if (value == null) {
    console.log(`Translation missing for key: ${fixedKey}`);
  }
}

The console output is Translation missing for key: Some\\nKey

So, my question is: In Javascript, how do I look up a value of a JSON key with new lines in the key?

Edit:

So, there were two problems with my code - one external to the post, and one internal. The external problem is that the keys coming from the external data source were somehow malformed when doing lookups with newlines - no idea what, but they were. The second issue was with creating fixedKey - JSON.stringify adds " characters to the start and end, so my console output that I originally put was a lie because I wasn't copy/pasting but recreating by hand - I had missed that the output was actually Translation missing for key: "Some\\nKey". The resulting fix was const fixedKey = JSON.stringify(key).replace(/^"/, "").replace(/"$/,""); - using Stringify and stripping the leading and trailing " characters.

CodePudding user response:

This works for me. Not sure what your issue is

const key = "Some Key";
const jsonString = `{ "Some\\nKey": "Some\\nvalue", "Some nice key": "Some nice value" }`
const obj = JSON.parse(jsonString.replaceAll(/\\n/g," "))
console.log(obj[key])

This also works but shows the value with a newline

const key = "Some\nKey";
const jsonString = `{ "Some\\nKey": "Some\\nvalue", "Some nice key": "Some nice value" }`
const obj = JSON.parse(jsonString)
console.log(obj[key])

CodePudding user response:

If your keys and values are the same, it shouldn't matter that there's a \n in the key or not.

const translations = {
  "test\n1": 1,
  "test\\n2": 2
};

console.log(translations["test\n1"]);
console.log(translations["test\\n2"]);

  • Related