0

I have the following String var input:

val json= """[{"first": 1, "name": "abc", "timestamp": "2018/06/28"},
             {"first": 2, "name": "mtm", "timestamp": "2018/06/28"}]"""

I need to remove key value(timestamp)

expected output:

val result= "[{"first": 1, "name": "abc"},{"first": 2, "name": "mtm"}]"

please kindly help.

Neo-coder
  • 7,715
  • 4
  • 33
  • 52
Rjj
  • 249
  • 1
  • 7
  • 22

2 Answers2

3

A simple regex will do it:

json.replaceAll(""",\s*"timestamp"[^,}]*""", "")
Tim
  • 26,753
  • 2
  • 16
  • 29
  • do JSONs preserve order? e.g. what if timestamp is the first key (where the first comma will be missing), as it may be in the future? – joel Jul 02 '18 at 12:09
  • 2
    @JoelBerkeley Yes, this is a specific answer to this situation. It won't work if "timestamp" is the first key, or if there are `,` or `}` characters embedded in the value. Better to use a JSON library in the general case – Tim Jul 02 '18 at 12:16
1

Or with a JSON parser, (though it's quite hard to answer w/o knowing what JSON parser you're using), perhaps

  • parse it, with one of these What JSON library to use in Scala?
  • then remove the "timestamp" entries with e.g. List.map(m => m - "timestamp") (depends on which library you're using)
  • recompile the JSON
joel
  • 6,359
  • 2
  • 30
  • 55