Gursi-ng
Gursi-ng

Reputation: 29

getting error "TypeError: must be str, not dict" when substituting variable into jsonpath_ng find string

Hi hope someone can help . I am fairly new to python and would like to pass a variable to a jsonpath_ng find function. In my code if I hardcode the json filter it works and I get a result and the expression type is "jsonpath_ng.jsonpath.Child" but if I build a variable using f-string then the type is str. So I think this is the reason the 2nd script it not parsing the jsonpath expression in the variable. Any help would be great ! Thanks

code:

import json
from jsonpath_ng.ext import parse

with open('./movies.json') as movies_json:
    movies = json.load(movies_json)

jsonpath_expression = parse("$.movies[1]")
print('jsonpath_expression type is', type(jsonpath_expression))
for match in jsonpath_expression.find(movies):
    print(match.value)

result:

jsonpath_expression type is <class 'jsonpath_ng.jsonpath.Child'> {'title': 'Pulp Fiction', 'director': 'Quentin Tarantino', 'year': 1994, 'cast': ['John Travolta', 'Uma Thurman', 'Samuel L. Jackson', 'Bruce Willis']}

BUT if I try and pass an index value to the jsonpath expression the type changes to str and I get an error

code:

import json
from jsonpath_ng.ext import parse

with open('./movies.json') as movies_json:
    movies = json.load(movies_json)

recno = str(1)
query_main = f'parse("$.movies[{recno}]")'
jsonpath_expression = query_main
print('query main output is', (query_main))
print('query main type is', type(query_main))
print('jsonpath_expression type is', type(jsonpath_expression))
for match in jsonpath_expression.find(movies):
    print(match.value)

result:

query main output is parse("$.movies[1]")
query main type is <class 'str'>
**jsonpath_expression type is <class 'str'>**
Traceback (most recent call last):
  File .\test.py line 13, in <module>
    for match in jsonpath_expression.find(movies):
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: must be str, not dict

I have tried building the variable in many different ways as I thought the square brackets in the expression were being interpretted as a dictionary but I don't think that is the case.

Upvotes: 1

Views: 99

Answers (1)

FahimSifnatul
FahimSifnatul

Reputation: 51

It's nothing but formatting issue. Just change your format string from

query_main = f'parse("$.movies[{recno}]")'

to

query_main = parse(f"$.movies[{recno}]").

You will get the result as expected.

Upvotes: 0

Related Questions