I have the below JSON. I want to search each array, and only scrape the data from the array which has keys and values in the "source" block, ignoring arrays which have an empty "source" block.
Here is the JSON:
{
"L": [
{
"operation_no": 123456,
"key1": "value1",
"keys": {
"no_seq": "1234",
"external_key": null
},
"key2": 10234,
"territory": {
"territory_no": 1
},
"key3": "value",
"source": []
},
{
"operation_no": 123458,
"key1": "value3",
"keys": {
"no_seq": "1237",
"external_key": null
},
"key2": 10237,
"territory": {
"territory_no": 1
},
"key3": "value",
"source": [
{
"source1": "fhry4645fsgaa1",
"source2": "123egst36535a1"
},
{
"source1": "fhry4645fsgaa2",
"source2": "123egst36535a2"
}
]
}
]
}
So, for example, the lower array which has "source" keys and values, I want to get the "operation_no" value (123458), but ignore the "operation_no" value thats has an empty "source" block (the first array).
How would I go about this using Python?
2
Answers
You can check for the length of "source", if it’s not equal to 0, add it to a new list (here "usable_data) to work with it later. You can also add it to a new dictionary, of course.
The JSON data is presumably available as a string (perhaps from a file). Once you have the JSON as a string then:
Output: