Reputation: 737
I actually receiving a json via API that contains several Arrays with different informations. Two of the Arrays are indirect linked. Array 1 contains an element that refers on the Array Position of an element in Array 2. I am actually transforming that json to fits the requested requirements and to move it to a database. It is necessary to link the Information of both Arrays later in the database. So my idea is to add an element with the array position into the array 2.
Example:
original Array one:
{
"country": [
{
"ContinentCode": "EU",
"ContinentGroup": 1,
"CountryCode": "DE",
"CountryName": "Germany",
"CurrencyIndex": 1
},
{
"ContinentCode": "AM",
"ContinentGroup": 2,
"CountryCode": "CA",
"CountryName": "Canada",
"CurrencyIndex": 2
}
]
}
Array original two:
{
"currency": [
{
"CODE": "EUR",
"Name": "Euro"
},
{
"Code": "CAD",
"Name": "Canadian Dollar"
}
]
}
Idea of the new array two:
{
"currency": [
{
"CODE": "EUR",
"Name": "Euro",
"Position": 1
},
{
"Code": "CAD",
"Name": "Canadian Dollar",
"Position": 2
}
]
}
I use jq 1.5 under a Windows environment. I took a look in the manual but found no built in Feature to add Array Position into the element. Any ideas?
regards Timo
Upvotes: 2
Views: 584
Reputation: 116880
To add the array index to the array elements in arr2.json, you could use reduce
:
jq -f program.jq arr2.json
where program.jq contains:
.currency |= reduce range(0;length) as $i (.; .[$i].Position = 1+$i)
Or, assuming you're in a Windows environment:
jq ".currency |= reduce range(0;length) as $i (.; .[$i].Position = 1+$i)" arr2.json
Upvotes: 1
Reputation: 540
This is the example code of your requirement please run the code snippet and check your requirement
var json1 ="{\"country\": [ { \"ContinentCode\": \"EU\", \"ContinentGroup\": 1, \"CountryCode\": \"DE\", \"CountryName\": \"Germany\", \"CurrencyIndex\" : 1}, { \"ContinentCode\": \"AM\", \"ContinentGroup\": 2, \"CountryCode\": \"CA\", \"CountryName\": \"Canada\", \"CurrencyIndex\" : 2}]}";
var json2 = "{\"currency\": [ { \"Code\": \"EUR\", \"Name\": \"Euro\" }, { \"Code\": \"CAD\", \"Name\": \"Canadian Dollar\" }]}";
var jsonParsed1 = JSON.parse(json1);
var jsonParsed2 = JSON.parse(json2);
var json3 = [];
for(var i=0;i<jsonParsed1.country.length;i++){
var json3Object = {"Code":jsonParsed2.currency[i].Code,"Name":jsonParsed2.currency[i].Name,"Position":i+1};
json3.push(json3Object);
}
console.log(json3);
Upvotes: 0