Search code examples
jsonstringslicejqsubstr

jq substr() equivalent to format a value


Hope you are fine in these times.

I am floored with a problem and I hope you have more knowledge.

Using 'jq' I want to change all the dates from eg. 19731013 (string) to a 1973-10-13

[
    {
        "Mail": "john@example.com",
        "Name": "Smith",
        "Employee_Number": "000555",
        "First_Name": "John",
        "Company": "ACME",
        "Department": null,
        "Employment_Status": "Retiree",
        "Start_Date": "19770516",
        "Function_Start_Date": "19770516",
        "Group_Phone": "",
        "Job_Title": "Operations Manager Warehousing",
        "Sub_Group": "Exempts",
        "Location": "Tibuktu",
        "Organizational_Unit": null,
        "Date_of_Birth": "19560719",
        "Gender": "1"
    },
    {
        "Mail": "mary@example.com",
        "Name": "Smith",
        "Employee_Number": "000777",
        "First_Name": "Mary",
        "Company": "ACME",
        "Department": null,
        "Employment_Status": "Retiree",
        "Start_Date": "19770516",
        "Function_Start_Date": "19770516",
        "Group_Phone": "",
        "Job_Title": "Manager",
        "Sub_Group": "Exempts",
        "Location": "Tibuktu",
        "Organizational_Unit": null,
        "Date_of_Birth": "19560719",
        "Gender": "2"
    }
] 

Is it possible to use substr(.Start_Date,1,5)"-"substr(.Start_Date,6,2)"-"substr(.Start_Date,8,3) like with awk in a CSV?

Maybe I am staring at a wall while missing the door on the right?

UPDATE: Thanks a lot guys this worked like a charm!

jq -r '.[].Start_Date |= "\(.[0:4])-\(.[4:6])-\(.[6:8])" | .[].Function_Start_Date |= "\(.[0:4])-\(.[4:6])-\(.[6:8])" | .[].Date_of_Birth|="\(.[0:4])-\(.[4:6])-\(.[6:8])"' employees.json > test.json

Solution

  • In JQ we have string slice and string interpolation syntaxes for that.

    $ jq '.[].Start_Date | "\(.[0:4])-\(.[4:6])-\(.[6:8])"' file
    "1977-05-16"
    "1977-05-16"