Skip to content

Enable setting json root via json pointer #1448

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -103,4 +103,26 @@ private Document parseJsonNode(JsonNode jsonNode, ObjectMapper objectMapper) {
return new Document(content, metadata);
}

public List<Document> get(JsonNode rootNode) {
if (rootNode.isArray()) {
return StreamSupport.stream(rootNode.spliterator(), true)
.map(jsonNode -> parseJsonNode(jsonNode, objectMapper))
.toList();
}
else {
return Collections.singletonList(parseJsonNode(rootNode, objectMapper));
}
}

public List<Document> get(String pointer) {
try {
JsonNode rootNode = objectMapper.readTree(this.resource.getInputStream());
rootNode = rootNode.at(pointer);
return get(rootNode);
}
catch (IOException e) {
throw new RuntimeException(e);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,14 @@
@SpringBootTest
public class JsonReaderTests {

@Value("classpath:person.json")
private Resource ObjectResource;

@Value("classpath:bikes.json")
private Resource arrayResource;

@Value("classpath:person.json")
private Resource ObjectResource;
@Value("classpath:events.json")
private Resource eventsResource;

@Test
void loadJsonArray() {
Expand All @@ -56,4 +59,26 @@ void loadJsonObject() {
}
}

@Test
void loadJsonArrayFromPointer() {
assertThat(arrayResource).isNotNull();
JsonReader jsonReader = new JsonReader(eventsResource, "description");
List<Document> documents = jsonReader.get("/0/sessions");
assertThat(documents).isNotEmpty();
for (Document document : documents) {
assertThat(document.getContent()).isNotEmpty();
assertThat(document.getContent()).contains("Session");
}
}

@Test
void loadJsonObjectFromPointer() {
assertThat(ObjectResource).isNotNull();
JsonReader jsonReader = new JsonReader(ObjectResource, "name");
List<Document> documents = jsonReader.get("/store");
assertThat(documents).isNotEmpty();
assertThat(documents.size()).isEqualTo(1);
assertThat(documents.get(0).getContent()).contains("name: Bike Shop");
}

}
15 changes: 15 additions & 0 deletions spring-ai-core/src/test/resources/events.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[
{
"sessions": [
{
"description": "Session one"
},
{
"description": "Session two"
},
{
"description": "Session three"
}
]
}
]