New to development. I am trying to grep the values from JSON file. Can some one help me on this.
[{
"State": "New York",
"City": "Queens",
"Cars": {
"gas": {
"USAMade": {
"Ford": ["Fordcars", "Fordtrucks", "Fordsuv"]
},
"OutsideUS": {
"Toyota": ["Tcars", "Ttrucks", "TSUV"]
}
},
"electric": {
"USAMade": {
"Tesla": ["model3", "modelS", "modelX"]
},
"OutsideUS": {
"Nissan": ["Ncars", "Ntrucks", "NSUV"]
}
}
}
},
{
"State": "Atlanta",
"City": "Roswell",
"Cars": {
"gas": {
"USAMade": {
"Ford": ["Fordcars", "Fordtrucks", "Fordsuv"]
},
"OutsideUS": {
"Toyota": ["Tcars", "Ttrucks", "TSUV"]
}
},
"electric": {
"USAMade": {
"Tesla": ["model3", "modelS", "modelX"]
},
"OutsideUS": {
"Nissan": ["Ncars", "Ntrucks", "NSUV"]
}
}
}
}
]
- How to list the type of cars like ( gas/electric)?
- once i get the type, i want to list the respective country of made ( USAMade/OutsideUS).
- After that i want to list the models ( Ford/Toyota)?
CodePudding user response:
Lets suppose you have the documents in the file test.json , here it is how to grep using linux shell tools cat,jq,sort,uniq:
1) cat test.json | jq '.[] | .Cars | keys[] ' | sort | uniq
"electric"
"gas"
2) cat test.json | jq '.[] | .Cars[] | keys[] ' | sort | uniq
"OutsideUS"
"USAMade"
3) cat test.json | jq '.[] | .Cars[][] | keys[] ' | sort | uniq
"Ford"
"Nissan"
"Tesla"
"Toyota"
If your data is in mongoDB , I suggest you keep this distinct values in single document in separate collection and populate the frontend page on load from this collection and the document can look something like this:
{
State:["Atlanta","Oregon"],
City:["New York" , "Tokio" , "Moskow"],
Location:["OutsideUS" ,"USAMade"],
Model:["Ford","Toyota","Nissan"]
}
You don't need to extract distinct values from database every time your front page loads since it is not scalable solution and at some point it will become performance bottleneck ...
But if you want it anyway to get only the distinct keys from mongoDB based on selection you can do as follow:
1.
mongos> db.test.aggregate([ {"$project":{"akv":{"$objectToArray":"$Cars"}}} ,{$unwind:"$akv"} ,{ $group:{_id:null , "allkeys":{$addToSet:"$akv.k"} } }] ).pretty()
{ "_id" : null, "allkeys" : [ "gas", "electric" ] }
mongos> db.test.aggregate([ {"$project":{"akv":{"$objectToArray":"$Cars.gas"}}} ,{$unwind:"$akv"} ,{ $group:{_id:null , "allkeys":{$addToSet:"$akv.k"} } }] ).pretty() { "_id" : null, "allkeys" : [ "USAMade", "OutsideUS" ] }
mongos> db.test.aggregate([ {"$project":{"akv":{"$objectToArray":"$Cars.gas.USAMade"}}} ,{$unwind:"$akv"} ,{ $group:{_id:null , "allkeys":{$addToSet:"$akv.k"} } }] ).pretty()
{ "_id" : null, "allkeys" : [ "Ford" ] }