Search code examples
pythonjsonjsonpathjsonpath-ng

Python jsonpath-ng : How to build a json document from jsonpath and values?


Developing in python, I would like to create a json document (tree) from a list of jsonpath and corresponding values.

For example, from the jsonpath

"$.orders[0].client" 

and a value "acme", it would create:

{'orders':[{'client':'acme'}]}

And then, I should be able to add a new node in the json document, at the location specified by another jsonpath with a given value. For example adding jsonpath $.orders[0].orderid and value "123", this would result in an updated json document:

{'orders':[{'client':'acme', 'orderid' : 123}]}

I have tried to understand jsonpath-ng for that purpose, but I don't understand how I could use it for that purpose (and not even if this is possible).

Anyone who could help?

Thanks in advance,

Best regards,

Laurent


Solution

  • If I understand your question correctly you are asking for a JSON to JSON transformation. JSONPath is not the right tool then. There are specialized libraries for this, e.g. JSONBender. You can transform some JSON like this:

    import json
    from jsonbender import bend, K, S
    
    MAPPING = {
        'client': S('orders', 0, 'client'),
        'orderid': S('orders', 0, 'orderid')
    }
    
    source = {
       "orders" : [
          {
             "orderid": 123,
             "client" : "acme"
          },
          {
             "orderid": 321,
             "client" : "two"
          }
       ]
    }
    
    result = bend(MAPPING, source)
    print(json.dumps(result))
    

    {"client": "acme", "orderid": 123}

    You can certainly bend the result even further but simpler output might work even better.