1

I have json paths from the results of search. I'm wondering how do I write to the particular path?

doc = {'foo':{ 'cd': {'baz': 1}, 'cd2': {'baz': 2}}}
expression = "foo.*.baz"
jsonpath_expr = parse(expression)
values = [str(match.full_path) for match in jsonpath_expr.find(doc)]
>> [foo.cd.baz, foo.cd2.baz]

for each of these results i want to insert a doc in its deep leaf like these

{'foo':{ 'cd': {'baz': 1, 'baz2': 2}, 'cd2': {'baz': 2, 'baz2': 2}}}

How do i go about these? I don't find any source of writing a value to a document given a json path. Thank you for the help.

1 Answer 1

1

This is how I did it.

def string_to_json(self, source):
      try:
        load_input_json = json.loads(source)
      except ValueError, e:
        raise Exception("Could not parse '%s' as JSON: %s" % (source, e))
      return load_input_json

  def _json_path_search(self, json, expr):
    path = parse(expr)
    return path.find(json)

  def update_json(self, doc, matches, name, value, index=0, parent=False):
    load_input_json = doc
    # matches = self._json_path_search(load_input_json, expr)
    datum_object = matches[int(index)]
    if not isinstance(datum_object, jsonpath.DatumInContext):
      raise Exception("Nothing found by the given json-path")
    path = datum_object.path
    if isinstance(path, jsonpath.Index):
      # datum_object.context.value[datum_object.path.index] = value
      datum_object.context.value[name] = value
    elif isinstance(path, jsonpath.Fields):
      # datum_object.context.value[datum_object.path.fields[0]] = value
      datum_object.context.value[name] = value
    return load_input_json
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.