Greg
Greg

Reputation: 61

A regex expression that can remove data from a json object

I'd like to be able to selectively remove elements from a json schema. Imagine a json object that contains a larger but similar array of users like this

[{
    "users": [{
        "firstName": "Nancy",
        "socialSecurityNumber": "123-45-6789",
        "sex": "Female",
        "id": "1234",
        "race": "Smith",
        "lastName": "Logan"
    }, {
        "firstName": "Charles",
        "socialSecurityNumber": "321-54-9876",
        "sex": "Male",
        "id": "3456",
        "race": "White",
        "lastName": "Clifford"
    }],

I'd like to strip the socialSecurityNumber element from the json schema using a regex expression. What would a regex expression to remove

"socialSecurityNumber": "whatever value",

look like where the value of the data pair could be any string?

I cannot be certain of the position of the data pair and whether it would have a trailing comma.

Upvotes: 0

Views: 2154

Answers (1)

Eduardo Poço
Eduardo Poço

Reputation: 3079

Try replacing the following regular expression with empty:

"socialSecurityNumber": "(\d|\-)",

It can go wrong if this info is split in 2 lines, or if the SSN is the last user field, because there will be no comma after it.

Anyway, after the replacing operation, check if there are any string

"socialSecurityNumber"

to confirm this can be used. If there are still strings that weren't replaced, then you will need a JSON parser to correctly eliminate this information.

Upvotes: 1

Related Questions