I have JSON file dumps and I need to push them into database. Table structure and everything is ready but I need to transform JSON to its equivalent table structure by converting the values of root-level keys into String irrespective of what is present in value ie integers, floats, strings, arrays of json or json objects.
Example to illustrate it.
{
"k1": 10,
"k2": "KEY2",
"k3": [],
"k4": -55.6,
"k6": { "k7": 1, "k8": [{ "k9": "true", "k10": "false" }] },
"k11": "THIS IS VERY LONG MESSAGE OF CHARACTERS UPTO 1024 BYTES"
}
and transformed JSON required as.
{
"k1": "10",
"k2": "KEY2",
"k3": "[]",
"k4": "-55.6",
"k6": "{ "k7": 1, "k8": [{ "k9": "true", "k10": "false" }] }",
"k11": "THIS IS VERY LONG MESSAGE OF CHARACTERS UPTO 1024 BYTES"
}
ie double qoutes around everything except string not touching the children of root-level values.
If a bash compatible code is available then it is very welcomed.
CodePudding user response:
The jq
tool can be put to good use here, if that's available to you:
$ jq 'map_values(if type == "number" then tostring else . end)' data.json
{
"k1": "10",
"k2": "KEY2",
"k3": [],
"k4": "-55.6",
"k6": {
"k7": 1,
"k8": [
{
"k9": "true",
"k10": "false"
}
]
},
"k11": "THIS IS VERY LONG MESSAGE OF CHARACTERS UPTO 1024 BYTES"
}
If you do want to make integers deeper in the structure into strings, there is also:
$ jq 'walk(if type == "number" then tostring else . end)' data.json
{
"k1": "10",
"k2": "KEY2",
"k3": [],
"k4": "-55.6",
"k6": {
"k7": "1",
"k8": [
{
"k9": "true",
"k10": "false"
}
]
},
"k11": "THIS IS VERY LONG MESSAGE OF CHARACTERS UPTO 1024 BYTES"
}
https://stedolan.github.io/jq/manual/v1.6/
CodePudding user response:
jq 'map_values(if type == "number" or type == "array" or type == "object" then tostring else . end)' input_json|sed 's/\\"/"/g'
{
"k1": "10",
"k2": "KEY2",
"k3": "[]",
"k4": "-55.6",
"k6": "{"k7":1,"k8":[{"k9":"true","k10":"false"}]}",
"k11": "THIS IS VERY LONG MESSAGE OF CHARACTERS UPTO 1024 BYTES"
}