Satya
Satya

Reputation: 29

How to remove object in JSON file via Linux command

I have JSON file which is placed into Linux server. I want to delete partcualr object from second position onward. Issues:-

  1. Root element keep it and same object which is repeated in JSON file has to be removed.
  2. how to append box brackets in JSON data

I tired sed and awk command but no luck

sed '/"audit"/,/}/ d; /^$/d' sample_request.json >> test.json -- It was deleting entire object instead of particular word.

audit -- Remove this object in json file from second position on wards. [] -- This box brakcets are needs to append to file which is show as excepted output

Actual :-

{
  "audit" : {
    "audit number" : "123",
    "amount" : {
      "Amount" : -10.0,
      "code" : "abc"
    },
    "over" : 1
  },
  "audit" : {
    "audit number" : "234",
    "amount" : {
      "Amount" : 290.0,
      "code" : "xyz"
    },
    "over" : 5
  },
  "audit" : {
    "audit number" : "235",
    "amount" : {
      "Amount" : 270.0,
      "code" : "kdb"
    },
    "over" : 6
  },
  "id" : "test",
  "eid" : "1",
  "bcode" : "123",
  "wid" : "1234",
  "wsid" : "11",
  "ss" : 2
  }

Excepted output like below:

{
  "audit" :[{
    "audit number" : "123",
    "amount" : {
      "Amount" : -10.0,
      "code" : "abc"
    },
    "over" : 1
  },
   {
    "audit number" : "234",
    "amount" : {
      "Amount" : 290.0,
      "code" : "xyz"
    },
    "over" : 5
  },
    {
    "audit number" : "235",
    "amount" : {
      "Amount" : 270.0,
      "code" : "kdb"
    },
    "over" : 6
  },
]
  "id" : "test",
  "eid" : "1",
  "bcode" : "123",
  "wid" : "1234",
  "wsid" : "11",
  "ss" : 2
  }

Upvotes: 0

Views: 1991

Answers (1)

lossleader
lossleader

Reputation: 13495

In sed, you can do something like:

sed -e '1,/audit number/s#audit".*#audit" : [{#' \
    -e '/audit number/,$s#"audit"\s*:##' \
    -e '{N;s#,\s*"id"#]&#;P;D}' input.txt

which roughly translates to:

  1. between lines 1 and the first "audit number" substitute A for audit fields.
  2. between the first "audit number" and the end, substitute B for audit fields.
  3. use line joining to find ,[spaces]"id" and insert the ']' before it.

Working with JSON with string tools is very dangerous as changes in spacing and order that are irrelevant between programs exchanging JSON will mess up this style of parsing. It is usually better to do a minimal amount of fixing to get to valid JSON and then use normal JSON facilities in a favorite programming language.

Upvotes: 1

Related Questions