Python - JsonPath在检索到的路径中插入值

时间:2017-01-17 21:01:30

标签: python jsonpath

我从搜索结果中获得了json路径。我想知道如何写出特定的路径?

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]

对于这些结果中的每一个,我想在这些

中深入插入一个doc
{'foo':{ 'cd': {'baz': 1, 'baz2': 2}, 'cd2': {'baz': 2, 'baz2': 2}}}

我如何解决这些问题?在给定json路径的情况下,我找不到向文档写入值的任何来源。谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

这就是我做到的。

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