1

I've been trying for a couple hours to do this, most questions and examples I've seen are not addressing my problem, for instance This one here is talking about the keys, not values.

I tired using the JSON parser, but there are two issues:

  1. How do I iterate through the values to begin with? I know there are different ways to read keys, but what about values and nested values (given that we don't know anything about what the keys or values are called).
  2. How to actually write the value and replace it, rather than replacing the whole file, maybe something like:

    key.value=key.value.toUpper();

I am looking for a solution that works for any JSON file, with absolultly no knowledge what the keys are called.

aero
  • 372
  • 1
  • 4
  • 18
  • #1 seems like basically a duplicate of [Access / process (nested) objects, arrays or JSON](https://stackoverflow.com/q/11922383/710446), in particular sections "*What if the property names are dynamic and I don't know them beforehand?*" and "*What if the "depth" of the data structure is unknown to me?*" – apsillers Oct 30 '17 at 17:37
  • #2: The string method you want is `.toUpperCase()`, but otherwise, yes, you'd do `obj.someProp = obj.someProp.toUpperCase()` as you suggest in your question – apsillers Oct 30 '17 at 17:40

1 Answers1

0

You could use replace to operate on the JSON string directly:

jsonString.replace(/"\s*:\s*"[^"]/g, match => {
  return match.slice(0, -1) + match[match.length - 1].toUpperCase()
})

That would save you from having to parse the JSON, and might be a bit faster. It can be tough to write a performant comprehensive RegEx though, so it might be safer just to parse the JSON and write a little recursive function:

const uppercaseValues = obj => {
  return Object.keys(obj).reduce((uppercased, key) => {
    const value = obj[key]
    if (typeof value === 'string') {
      uppercased[key] = value[0].toUpperCase() + value.slice(1)
    } else if (typeof value === 'object') {
      uppercased[key] = uppercaseValues(value)
    } else {
      uppercased[key] = value
    }
    return uppercased
  }, {})
}

const parsedJson = JSON.parse(jsonString)
const uppercased = uppercaseValues(parsedJson)
const xformedJson = JSON.stringify(uppercased)
Zac Delventhal
  • 3,543
  • 3
  • 20
  • 26