Joe
Joe

Reputation: 991

How to replace double backslash in a JSON text?

I've got this json file:

{
    "module": {
        "data": {
            "orderInfo_203759231000": {
                "fields": {
                    "createdAt": "Dipesan pada\\r\\n 17 Mei 2018",
                    "tradeOrderId": 203759231000
                }
            },
            "orderInfo_203759231000": {
                "fields": {
                    "createdAt": "Dipesan pada\\r\\n 22 Mei 2018",
                    "tradeOrderId": 203759231000
                }
            },
            "orderInfo_203759231000": {
                "fields": {
                    "createdAt": "Dipesan pada\\r\\n 22 Mei 2018",
                    "tradeOrderId": 203759231000
                }
            },
            "orderInfo_203759231000": {
                "fields": {
                    "createdAt": "Dipesan pada\\r\\n 22 Mei 2018",
                    "tradeOrderId": 203759231000
                }
            },
            "orderInfo_203759231000": {
                "fields": {
                    "createdAt": "Dipesan pada\\r\\n 22 Mei 2018",
                    "tradeOrderId": 203759231000
                }
            }
        }
    }
}

and I want to remove Dipesan pada\\r\\n here's what I have tried:

sed 's/Dipesan pada \\\\r\\\\n//g' file.json

But it doesn't work, I want the end result to only be the dates like this:

"createdAt": "17 Mei 2018",
"createdAt": "22 Mei 2018",
"createdAt": "22 Mei 2018",
etc...

How should I fix it?

Upvotes: 2

Views: 1816

Answers (2)

Inian
Inian

Reputation: 85620

Using jq with update operator and sub filter, you can do it as below. The slashes need to escaped twice to make it work

jq '(.module.data[].fields.createdAt)|=(sub("Dipesan pada\\\\r\\\\n ";""))' input.json

As tested on jq-play. This is tested on your JSON input with keys modified to avoid duplication.

Upvotes: 1

Thomas
Thomas

Reputation: 181785

Your backslashes are fine, congratulations! The issue is with the placement of a single pesky space:

sed 's/Dipesan pada \\\\r\\\\n//g' file.json # bad
sed 's/Dipesan pada\\\\r\\\\n //g' file.json # good

Upvotes: 2

Related Questions