Is it possible to sort the following kind of nested JSON in python3 based on the Key "age"
{
"barcelona":[
{
"age":29,
"name":"john"
}
],
"london":[
{
"age":23,
"name":"bob"
}
],
"mancherster":[
{
"age":23,
"name":"shaw"
}
],
"paris":[
{
"age":45,
"name":"bony"
},
{
"age":16,
"name":"paul"
}
]
}
Thanks in advance for your responses
I suppose you just want to sort the lists for each city? In that case this should work:
import json
json_str = "<your json string>"
json_obj = json.loads(json_str)
by_age = { key: sorted(value, key=lambda v: v['age']) for key, value in json_obj.items() }
Btw, there are errors in the JSON you posted - trailing commas (the commas at the end of "name": "whatever", in this case) are not allowed. You need to remove them to avoid an error at the json.loads call.
Related
I am trying to parse the JSON file below. The problem is I cannot return "Mountpoint" as a key. It only gets parsed as a value. This is the command I am using to parse it json_data = JSON.parse(readjson). The reason I guess that it's a key is because if I run json_data.keys only EncryptionStatus and SwitchName are returned. Any help would be greatly appreciated.
{
"EncryptionStatus": [
{
"MountPoint": "C:",
"VolumeStatus": "FullyEncrypted"
},
{
"MountPoint": "F:",
"VolumeStatus": "FullyEncrypted"
},
{
"MountPoint": "G:",
"VolumeStatus": "FullyEncrypted"
},
{
"MountPoint": "H:",
"VolumeStatus": "FullyEncrypted"
}
],
"SwitchName": [
"LAN",
"WAN"
]
}
I tried using dig as a part of my JSON.parse but that didn't seem to help me.
JSON data can have multiple levels.
Your JSON document is a
Hash (Dictionary/Map/Object in other languages) that has two keys ("EncryptionStatus", "SwitchName"),
The value for the "EncryptionStatsu" key is an Array of Hashes (with keys "MountPoint" and "VolumeStatus").
# assuming your JSON is in a file called "input.json"
data = File.read("input.json")
json = JSON.parse(data)
json["EncryptionStatus"].each do |encryption_status|
puts "#{encryption_status["MountPoint"]} is #{encryption_status["VolumeStatus"]}"
end
This will print out
C: is FullyEncrypted
F: is FullyEncrypted
G: is FullyEncrypted
H: is FullyEncrypted
If you want to access a specific item you can look at the dig method. E.g.
json.dig("EncryptionStatus", 3)
Would return the information for mountpoint "H"
I have below JSON and want to fetch the value of "person1" and "person2" either into a map as a key-value pair or individually is also fine.
Expected Output: [attributes:["person1": "ROBERT", "person2": "STEVEN"]]
I started with JSON parsing and dont really have idea on what to do next?
def parsedJSON= new groovy.json.JsonSlurper().parseText(body)
JSON
"permutationsRequest":{
"attributes":[
{
"name":"person1",
"value":"ROBERT"
},
{
"name":"person2",
"value":"STEVEN"
}
]
}
}
def map = parsedJSON.permutationsRequest.attributes.collectEntries{ [it.name,it.value] }
println map.person2
I am newto the scala language to i am trying to read the json file in my scala file using jackson library
my son file is like this
{
"Rice":[
{
"name":"Basmati",
"price":40
},
{
"name":"jeera",
"price":30
},
{
"name":"Indrayani",
"price":40
}
],
"Pulses":[
{
"name":"peas",
"price":60
},
{
"name":"ground nut",
"price":60
},
{
"name":"dal",
"price":80
}
],
"Wheats":[
{
"name":"atta",
"price":40
},
{
"name":"bread",
"price":45
},
{
"name":"bun",
"price":50
}
]
}
I tried with the case classes to store and print the data
code sample like this
case class Inventory(var name:String,var price:String)
object InventoryDataManagement {
def main(args: Array[String]): Unit = {
val mapper = JsonMapper.builder()
.addModule(DefaultScalaModule)
.build()
val src = new File("src/main/json/inventary.json")
val myMap = mapper.readValue(src,classOf[Inventory])
println(myMap.name)
}
}
but I am getting error like below
Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "Rice" (class Inventory), not marked as ignorable (2 known properties: "price",
"name"])
please help to understand this
thanks in advance!!!
Unrecognized field "Rice" (class Inventory)
This error should make you notice that Jackson is looking for a field Rice on the Inventory class, which doesn't make sense.
Why so?
Because you are telling Jackson to read your JSON file as a single Inventory instance.
This is not what your JSON file contains, it contains something that can be represented as a Map[String, Seq[Inventory]].
You should try something like this instead:
mapper.readValue(src,classOf[Map[String, Seq[Inventory]]])
Here is my sample JSON data:
var testData =
{
"Level1": [
{
"Level2": [
{
"Level3": [
{
"body": "AAAAA"
},
{
"body": "BBBBB"
}
]
}
]
}
]
};
When I use JSON.stringify like this:
var x = JSON.stringify(testData).replace(/[\[\]]/g,"");
console.log(x);
It works as expected and correctly replaces the square brackets and returns this result:
{"Level1":{"Level2":{"Level3":{"body":"AAAAA"},{"body":"BBBBB"}}}}
The error occurs when I try to add JSON.parse like this which returns an error:
var x = JSON.parse(JSON.stringify(testData).replace(/[\[\]]/g,""));
The specific error is SyntaxError: Unexpected token { in JSON. What seems to be happening is that JSON.parse is treating the comma inside the key/value list as the end of the JSON string, when it is not the end.
Does anyone have any idea why this is happening?
{"Level1":{"Level2":{"Level3":{"body":"AAAAA"},{"body":"BBBBB"}}}}
This is not valid JSON
The level 3 should be:
"Level3":[{"body":"AAAAA"}, {"body":"BBBBB"}]
For you first levels, you have arrays with only 1 element, so the array brackets [] kan be removed without consequence. The level 3 is an actual array with 2 elements, so removing the [] breaks your valid JSON syntax.
I am trying to parse a mongodb query in json to dictionary and the JObject.Parse throws exception.
The JSON string is something like below
{ vendor: "xyx", product: { $in : [ /prod1/i, /prod2/i, /prod3/i ] } }
The exception is message is
Error parsing comment. Expected: *, got p. Path 'product.$in', line 1, position 50.
JSON doesn't have support for regular expressions but you could change your JSON string to use the $regex query operator syntax instead:
{ vendor: "xyx", product: { $in: [
{$regex: "prod1", $options: "i"},
{$regex: "prod2", $options: "i"},
{$regex: "prod3", $options: "i"}
] } }
All in one string, of course. And to be valid JSON, the keys all need to be quoted too, but JObject.Parse may allow them to be omitted as it doesn't sound like that part was giving you trouble.
Looks like you didn't mean to say JSON, but rather MongoDB, no?
For MongoDB queries, you need to do this:
{ vendor: "xyx", product: { $in : [ Pattern.compile(/prod1/i), Pattern.compile(/prod2/i), Pattern.compile(/prod3/i) ] } }