We have a requirement to create JSON object from the various JSONPaths that are provided. For example below are two paths and the values of that path that are there in the new JSON object to be created.
$.student.firstName = "Abc"
$.student.subject['physics'].mark=100
Is there any java open source library which helps to create the result object just from this path?
{
"student":{
"firstName":"Abc",
"physics":{
"mark":100
}
}
}
We explored certain libraries like JSONPath. It has option to parse the JSON file, but doesn't have option to recursively create the JSON file from the path.
Based in this fork from JsonPath that add the feature to create a new json node from a json path, you can do something like this:
// columnsMap = key: jsonPath node, value: value to be added to node
String json = "{ }";
for (Entry<String, String> entry : columnsMap.entrySet()) {
JsonPath compiledPath = JsonPath.compile(entry.getKey());
Object parsedJsonPath =
compiledPath.set(configuration.jsonProvider().parse(json), entry.getValue(), configuration);
json = JsonPath.parse(parsedJsonPath).jsonString();
}
return json;
Input (columnsMap):
{vendor_account_ids=1234567,4567123,789785,
charges[0].vendor_charge_id=CHARGE-01,
charges[1].vendor_charge_id=CHARGE-02,
charges[0].type=LOAN_DEDUCTION,
charges[0].conditions.alternative_delivery_date=false,
charges[0].conditions.depends_on_vendor_charge_ids[0]=ID01,
charges[0].conditions.depends_on_vendor_charge_ids[1]=ID02,
charges[0].conditions.order_total.maximum_value=123.45,
charges[0].conditions.payment_method=BANK_SLIP,
charges[0].conditions.scaled_from=ORDER_TOTAL,
charges[0].conditions.product_attributes.is_alcoholic=false,
charges[0].conditions.payment_terms[0]=1,
charges[0].conditions.payment_terms[1]=30,
charges[0].output.scope=LINE_ITEM,
charges[0].output.apply_to=DISCOUNT_AMOUNT,
charges[0].output.type=PERCENT,
charges[0].output.ratio=FIXED,
charges[0].output.ranges[0].from=1,
charges[0].output.ranges[0].value=10,
charges[0].output.vendor_item_ids[0]=SKU001,
charges[0].output.vendor_item_ids[1]=SKU002
}
Output (returned json):
{
"vendor_account_ids": "1234567,4567123,789785",
"charges": [
{
"vendor_charge_id": "CHARGE-01",
"type": "LOAN_DEDUCTION",
"conditions": {
"alternative_delivery_date": "false",
"depends_on_vendor_charge_ids": [
"ID01",
"ID02"
],
"order_total": {
"maximum_value": "123.45"
},
"payment_method": "BANK_SLIP",
"scaled_from": "ORDER_TOTAL",
"product_attributes": {
"is_alcoholic": "false"
},
"payment_terms": [
"1",
"30"
]
},
"output": {
"scope": "LINE_ITEM",
"apply_to": "DISCOUNT_AMOUNT",
"type": "PERCENT",
"ratio": "FIXED",
"ranges": [
{
"from": "1",
"value": "10"
}
],
"vendor_item_ids": [
"SKU001",
"SKU002"
]
}
},
{
"vendor_charge_id": "CHARGE-02"
}
]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With