├── .devcontainer └── devcontainer.json ├── .editorconfig ├── .github ├── renovate.json └── workflows │ ├── build.yml │ ├── githubpages.yaml │ ├── junie.yml │ ├── publish.yml │ └── pull_request.yaml ├── .gitignore ├── LICENSE ├── README.md ├── build.gradle.kts ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── knit.code.include ├── knit.properties ├── knit.test.template ├── libs.versions.toml ├── renovate.json ├── settings.gradle.kts └── src ├── commonMain └── kotlin │ └── io │ └── github │ └── nomisrev │ ├── JsonPath.kt │ ├── JsonPathEvery.kt │ ├── optics.kt │ └── selectUtils.kt ├── commonTest └── kotlin │ └── io │ └── github │ └── nomisrev │ ├── Arb.kt │ ├── JsonDSLSpec.kt │ └── KotestConfig.kt └── jvmTest └── kotlin ├── ReadMeSpec.kt └── example ├── example-readme-01.kt ├── example-readme-02.kt ├── example-readme-03.kt └── example-readme-04.kt /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Java", 3 | "image": "mcr.microsoft.com/devcontainers/java:1-21", 4 | "features": { 5 | "ghcr.io/devcontainers/features/java:1": { 6 | "version": "none", 7 | "installMaven": "true", 8 | "mavenVersion": "3.8.6", 9 | "installGradle": "true" 10 | } 11 | } 12 | } -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | [*.{kt,kts}] 2 | indent_size=2 3 | insert_final_newline=true 4 | max_line_length=off 5 | disabled_rules=import-ordering,no-unit-return,curly-spacing,indent 6 | -------------------------------------------------------------------------------- /.github/renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "lockFileMaintenance": { 3 | "enabled": true, 4 | "automerge": true 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: "Build" 2 | 3 | on: 4 | pull_request: 5 | paths-ignore: 6 | - '*.md' 7 | push: 8 | branches: 9 | - main 10 | 11 | jobs: 12 | check: 13 | runs-on: ubuntu-latest 14 | timeout-minutes: 30 15 | 16 | steps: 17 | - name: Checkout the repo 18 | uses: actions/checkout@v4 19 | with: 20 | fetch-depth: 0 21 | 22 | - name: Set up Java 23 | uses: actions/setup-java@v4 24 | with: 25 | distribution: 'zulu' 26 | java-version: 11 27 | 28 | - name: Build 29 | uses: gradle/gradle-build-action@v3 30 | with: 31 | arguments: build --scan --full-stacktrace 32 | 33 | - name: Bundle the build report 34 | if: failure() 35 | run: find . -type d -name 'reports' | zip -@ -r build-reports.zip 36 | 37 | - name: Upload the build report 38 | if: failure() 39 | uses: actions/upload-artifact@master 40 | with: 41 | name: error-report 42 | path: build-reports.zip 43 | -------------------------------------------------------------------------------- /.github/workflows/githubpages.yaml: -------------------------------------------------------------------------------- 1 | name: githubpages 2 | 3 | on: 4 | release: 5 | types: [published] 6 | 7 | jobs: 8 | githubpages: 9 | runs-on: ubuntu-latest 10 | timeout-minutes: 20 11 | 12 | steps: 13 | - uses: actions/checkout@v4 14 | with: 15 | fetch-depth: 0 16 | 17 | - name: Dokka 18 | id: Dokka 19 | run: ./gradlew -Pversion=${{ github.event.release.tag_name }} dokkaHtml 20 | 21 | - name: Deploy to gh-pages 22 | uses: peaceiris/actions-gh-pages@v4 23 | with: 24 | github_token: ${{ secrets.GITHUB_TOKEN }} 25 | publish_dir: ./docs 26 | -------------------------------------------------------------------------------- /.github/workflows/junie.yml: -------------------------------------------------------------------------------- 1 | name: Junie 2 | run-name: Junie run ${{ inputs.run_id }} 3 | 4 | permissions: 5 | contents: write 6 | pull-requests: write 7 | 8 | on: 9 | workflow_dispatch: 10 | inputs: 11 | run_id: 12 | description: "id of workflow process" 13 | required: true 14 | workflow_params: 15 | description: "stringified params" 16 | required: true 17 | 18 | jobs: 19 | call-workflow-passing-data: 20 | uses: jetbrains-junie/junie-workflows/.github/workflows/ej-issue.yml@main 21 | with: 22 | workflow_params: ${{ inputs.workflow_params }} 23 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: "Publish library" 2 | 3 | on: 4 | workflow_dispatch: 5 | branches: [main] 6 | inputs: 7 | version: 8 | description: 'Version' 9 | required: true 10 | type: string 11 | 12 | env: 13 | ORG_GRADLE_PROJECT_mavenCentralUsername: '${{ secrets.SONATYPE_USER }}' 14 | ORG_GRADLE_PROJECT_mavenCentralPassword: '${{ secrets.SONATYPE_PWD }}' 15 | ORG_GRADLE_PROJECT_signingInMemoryKeyId: '${{ secrets.SIGNING_KEY_ID }}' 16 | ORG_GRADLE_PROJECT_signingInMemoryKey: '${{ secrets.SIGNING_KEY }}' 17 | ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: '${{ secrets.SIGNING_KEY_PASSPHRASE }}' 18 | 19 | jobs: 20 | publish: 21 | timeout-minutes: 30 22 | runs-on: macos-latest 23 | steps: 24 | - uses: actions/checkout@v4 25 | with: 26 | fetch-depth: 0 27 | 28 | - name: Set up Java 29 | uses: actions/setup-java@v4 30 | with: 31 | distribution: 'zulu' 32 | java-version: 11 33 | 34 | - name: assemble 35 | uses: gradle/gradle-build-action@v3 36 | with: 37 | arguments: assemble -Pversion=${{ inputs.version }} 38 | 39 | - name: Upload reports 40 | if: failure() 41 | uses: actions/upload-artifact@v4 42 | with: 43 | name: 'reports-${{ matrix.os }}' 44 | path: '**/build/reports/**' 45 | 46 | - name: Publish final version 47 | uses: gradle/gradle-build-action@v3 48 | with: 49 | arguments: -Pversion=${{ inputs.version }} publishAllPublicationsToMavenCentralRepository 50 | -------------------------------------------------------------------------------- /.github/workflows/pull_request.yaml: -------------------------------------------------------------------------------- 1 | name: "Pull Request" 2 | 3 | on: [pull_request] 4 | 5 | jobs: 6 | build: 7 | runs-on: ubuntu-latest 8 | 9 | steps: 10 | - uses: actions/checkout@v4 11 | with: 12 | fetch-depth: 0 13 | 14 | - name: Set up Java 15 | uses: actions/setup-java@v4 16 | with: 17 | distribution: 'zulu' 18 | java-version: 11 19 | 20 | - name: Build 21 | uses: gradle/gradle-build-action@v3 22 | with: 23 | arguments: build 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.toptal.com/developers/gitignore/api/intellij+all,kotlin,gradle,macos 2 | # Edit at https://www.toptal.com/developers/gitignore?templates=intellij+all,kotlin,gradle,macos 3 | 4 | ### Intellij+all ### 5 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider 6 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 7 | 8 | # User-specific stuff 9 | .idea/**/workspace.xml 10 | .idea/**/tasks.xml 11 | .idea/**/usage.statistics.xml 12 | .idea/**/dictionaries 13 | .idea/**/shelf 14 | 15 | # AWS User-specific 16 | .idea/**/aws.xml 17 | 18 | # Generated files 19 | .idea/**/contentModel.xml 20 | 21 | # Sensitive or high-churn files 22 | .idea/**/dataSources/ 23 | .idea/**/dataSources.ids 24 | .idea/**/dataSources.local.xml 25 | .idea/**/sqlDataSources.xml 26 | .idea/**/dynamic.xml 27 | .idea/**/uiDesigner.xml 28 | .idea/**/dbnavigator.xml 29 | 30 | # Gradle 31 | .idea/**/gradle.xml 32 | .idea/**/libraries 33 | 34 | # Gradle and Maven with auto-import 35 | # When using Gradle or Maven with auto-import, you should exclude module files, 36 | # since they will be recreated, and may cause churn. Uncomment if using 37 | # auto-import. 38 | # .idea/artifacts 39 | # .idea/compiler.xml 40 | # .idea/jarRepositories.xml 41 | # .idea/modules.xml 42 | # .idea/*.iml 43 | # .idea/modules 44 | # *.iml 45 | # *.ipr 46 | 47 | # CMake 48 | cmake-build-*/ 49 | 50 | # Mongo Explorer plugin 51 | .idea/**/mongoSettings.xml 52 | 53 | # File-based project format 54 | *.iws 55 | 56 | # IntelliJ 57 | out/ 58 | 59 | # mpeltonen/sbt-idea plugin 60 | .idea_modules/ 61 | 62 | # JIRA plugin 63 | atlassian-ide-plugin.xml 64 | 65 | # Cursive Clojure plugin 66 | .idea/replstate.xml 67 | 68 | # Crashlytics plugin (for Android Studio and IntelliJ) 69 | com_crashlytics_export_strings.xml 70 | crashlytics.properties 71 | crashlytics-build.properties 72 | fabric.properties 73 | 74 | # Editor-based Rest Client 75 | .idea/httpRequests 76 | 77 | # Android studio 3.1+ serialized cache file 78 | .idea/caches/build_file_checksums.ser 79 | 80 | ### Intellij+all Patch ### 81 | # Ignores the whole .idea folder and all .iml files 82 | # See https://github.com/joeblau/gitignore.io/issues/186 and https://github.com/joeblau/gitignore.io/issues/360 83 | 84 | .idea/ 85 | 86 | # Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-249601023 87 | 88 | *.iml 89 | modules.xml 90 | .idea/misc.xml 91 | *.ipr 92 | 93 | # Sonarlint plugin 94 | .idea/sonarlint 95 | 96 | ### Kotlin ### 97 | # Compiled class file 98 | *.class 99 | 100 | # Log file 101 | *.log 102 | 103 | # BlueJ files 104 | *.ctxt 105 | 106 | # Mobile Tools for Java (J2ME) 107 | .mtj.tmp/ 108 | 109 | # Package Files # 110 | *.jar 111 | *.war 112 | *.nar 113 | *.ear 114 | *.zip 115 | *.tar.gz 116 | *.rar 117 | 118 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 119 | hs_err_pid* 120 | 121 | ### macOS ### 122 | # General 123 | .DS_Store 124 | .AppleDouble 125 | .LSOverride 126 | 127 | # Icon must end with two \r 128 | Icon 129 | 130 | 131 | # Thumbnails 132 | ._* 133 | 134 | # Files that might appear in the root of a volume 135 | .DocumentRevisions-V100 136 | .fseventsd 137 | .Spotlight-V100 138 | .TemporaryItems 139 | .Trashes 140 | .VolumeIcon.icns 141 | .com.apple.timemachine.donotpresent 142 | 143 | # Directories potentially created on remote AFP share 144 | .AppleDB 145 | .AppleDesktop 146 | Network Trash Folder 147 | Temporary Items 148 | .apdisk 149 | 150 | ### Gradle ### 151 | .gradle 152 | build/ 153 | 154 | # Ignore Gradle GUI config 155 | gradle-app.setting 156 | 157 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 158 | !gradle-wrapper.jar 159 | 160 | # Cache of project 161 | .gradletasknamecache 162 | 163 | # # Work around https://youtrack.jetbrains.com/issue/IDEA-116898 164 | # gradle/wrapper/gradle-wrapper.properties 165 | 166 | ### Gradle Patch ### 167 | **/build/ 168 | 169 | kotlin-js-store 170 | 171 | # End of https://www.toptal.com/developers/gitignore/api/intellij+all,kotlin,gradle,macos 172 | 173 | gradle-build-scan.txt 174 | .kotlin -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Module KotlinX Serialization JsonPath 2 | 3 | [![Maven Central](https://img.shields.io/maven-central/v/io.github.nomisrev/kotlinx-serialization-jsonpath?color=4caf50&label=latest%20release)](https://maven-badges.herokuapp.com/maven-central/io.github.nomisrev/kotlinx-serialization-jsonpath) 4 | [![Latest snapshot](https://img.shields.io/badge/dynamic/xml?color=orange&label=latest%20snapshot&prefix=v&query=%2F%2Fmetadata%2Fversioning%2Flatest&url=https%3A%2F%2Fs01.oss.sonatype.org%2Fservice%2Flocal%2Frepositories%2Fsnapshots%2Fcontent%2Fio%2Fgithub%2Fnomisrev%2Fkotlinx-serialization-jsonpath%2Fmaven-metadata.xml)](https://s01.oss.sonatype.org/service/local/repositories/snapshots/content/io/github/nomisrev) 5 | 6 | JsonPath offers a simple DSL to work with JsonElement from Kotlinx Serialization Json, 7 | this allows you to easily work with JSON in Kotlin in a typed manner. 8 | Simply add the following dependency as `implementation` in the `build.gradle` dependencies` block. 9 | 10 | ```groovy 11 | dependencies { 12 | implementation("io.github.nomisrev:kotlinx-serialization-jsonpath:0.2.0") 13 | } 14 | ``` 15 | 16 | Let's dive right in with following `JSON_STRING` as input `JsonElement` that models a simple company. 17 | 18 | 19 | 20 | ```json 21 | { 22 | "name": "Arrow", 23 | "address": { 24 | "city": "Functional Town", 25 | "street": { 26 | "number": 1337, 27 | "name": "Functional street" 28 | } 29 | }, 30 | "employees": [ 31 | { 32 | "name": "John", 33 | "lastName": "doe" 34 | }, 35 | { 36 | "name": "Jane", 37 | "lastName": "doe" 38 | } 39 | ] 40 | } 41 | ``` 42 | 43 | Given this `JsonElement` we can _select_ the `name` from the `JsonElement`. 44 | This gives us an `Optional` from the _root_ `JsonElement` to the `name` property with type `String`. 45 | We can then use this _JsonPath_ to _modify_ the original `JsonElement`'s `name` property, 46 | this gives us back _a new_ `JsonElement` with the _name_ modified according to the passed `String::uppercase` function. 47 | 48 | 53 | ```kotlin 54 | val json: JsonElement = Json.decodeFromString(JSON_STRING) 55 | val name: Optional = JsonPath.select("name").string 56 | println(name.modify(json, String::uppercase)) 57 | ``` 58 | > You can get the full code [here](src/jvmTest/kotlin/example/example-readme-01.kt). 59 | 60 | ```text 61 | {"name":"ARROW","address":{"city":"Functional Town","street":{"number":1337,"name":"Functional street"}},"employees":[{"name":"John","lastName":"doe"},{"name":"Jane","lastName":"doe"}]} 62 | ``` 63 | 64 | As we've seen above we can _select_ a property from a _JsonObject_, 65 | but what if we want to access deeply nested properties in our `JsonElement`? 66 | For that we can use _path_ which allows you to _select_ deeply nested properties using the _dot (.) notation_ you might know from Javascript. 67 | 68 | Below we _select_ the _address_ `JsonObject`, 69 | and from the _address_ `JsonObject` we then _select_ the _street_ `JsonObject`, 70 | to then finally _select_ the _name_ of the _street_. 71 | 72 | This again returns us an `Optional`, which we use to _modify_ the `address.street.name`. 73 | We then also _extract_ the value using `getOrNull` which returns us the desired _path_ in our `JsonElement`, 74 | or it returns _null_ if the desired _path_ is not available in our `JsonElement`. 75 | 76 | 77 | 78 | 83 | ```kotlin 84 | val json: JsonElement = Json.decodeFromString(JSON_STRING) 85 | val name: Optional = JsonPath.path("address.street.name").string 86 | val res: JsonElement = name.modify(json, String::uppercase).also(::println) 87 | name.getOrNull(res)?.also(::println) 88 | ``` 89 | > You can get the full code [here](src/jvmTest/kotlin/example/example-readme-02.kt). 90 | 91 | ```text 92 | {"name":"Arrow","address":{"city":"Functional Town","street":{"number":1337,"name":"FUNCTIONAL STREET"}},"employees":[{"name":"John","lastName":"doe"},{"name":"Jane","lastName":"doe"}]} 93 | FUNCTIONAL STREET 94 | ``` 95 | 96 | In the previous examples we've seen how we can select properties out of `JsonObject`, 97 | but when working with `JsonElement` we also often have to deal with `JsonArray` that can contain many `JsonElement`. 98 | For these use-cases we can use `every`, which focuses into _every_ `JsonElement` in our `JsonArray`. 99 | 100 | In the example below we select the _employees_ `JsonArray`, 101 | and then we select _every_ `JsonElement` in the `JsonArray`. 102 | We then _select_ the _name_ out of _every_ `JsonElement`. 103 | 104 | Instead of `Optional` it now returns `Traversal`, 105 | since we selected _many properties_ instead of a _single property_. 106 | 107 | Just like before we can apply a function to it using _modify_, 108 | and we can also _extract every property_ using `getAll`. 109 | This returns us an `emptyList()` when no values were found along the _path_, 110 | or all found values inside a `List`. 111 | 112 | 113 | 114 | 119 | ```kotlin 120 | val json: JsonElement = Json.decodeFromString(JSON_STRING) 121 | val employeesName: Traversal = JsonPath.select("employees").every.select("name").string 122 | val res: JsonElement = employeesName.modify(json, String::uppercase).also(::println) 123 | employeesName.getAll(res).also(::println) 124 | ``` 125 | > You can get the full code [here](src/jvmTest/kotlin/example/example-readme-03.kt). 126 | 127 | ```text 128 | {"name":"Arrow","address":{"city":"Functional Town","street":{"number":1337,"name":"Functional street"}},"employees":[{"name":"JOHN","lastName":"doe"},{"name":"JANE","lastName":"doe"}]} 129 | [JOHN, JANE] 130 | ``` 131 | 132 | Alternatively we can also use the _pathEvery_ function to select _every_ `JsonElement` in our `JsonArray`. 133 | Like for _path_ we can also use the _dot (.) notation_ to select deeply nested properties. 134 | On the other hand, the _star (*) notation_ allow us to select _every_ `JsonElement` in our `JsonArray`. 135 | 136 | Like before, below we select the _employees_ `JsonArray`, 137 | and then we select _every_ `JsonElement` in the `JsonArray`. 138 | We then _select_ the _name_ out of _every_ `JsonElement`. 139 | 140 | Again, instead of `Optional` it now returns `Traversal`, 141 | since we selected _many properties_ instead of a _single property_. 142 | 143 | You can then, apply a function to it using _modify_ like before. 144 | 145 | 146 | 147 | 152 | ```kotlin 153 | val json: JsonElement = Json.decodeFromString(JSON_STRING) 154 | val employeesName: Traversal = JsonPath.pathEvery("employees.*.name").string 155 | val res: JsonElement = employeesName.modify(json, String::uppercase).also(::println) 156 | employeesName.getAll(res).also(::println) 157 | ``` 158 | > You can get the full code [here](src/jvmTest/kotlin/example/example-readme-04.kt). 159 | 160 | ```text 161 | {"name":"Arrow","address":{"city":"Functional Town","street":{"number":1337,"name":"Functional street"}},"employees":[{"name":"JOHN","lastName":"doe"},{"name":"JANE","lastName":"doe"}]} 162 | [JOHN, JANE] 163 | ``` 164 | -------------------------------------------------------------------------------- /build.gradle.kts: -------------------------------------------------------------------------------- 1 | import kotlinx.knit.KnitPluginExtension 2 | import org.jetbrains.kotlin.gradle.tasks.KotlinCompile 3 | import io.gitlab.arturbosch.detekt.Detekt 4 | import io.gitlab.arturbosch.detekt.extensions.DetektExtension 5 | import org.gradle.api.JavaVersion.VERSION_11 6 | import org.gradle.api.tasks.testing.logging.TestExceptionFormat 7 | import org.gradle.api.tasks.testing.logging.TestLogEvent.FAILED 8 | import org.gradle.api.tasks.testing.logging.TestLogEvent.SKIPPED 9 | import org.gradle.api.tasks.testing.logging.TestLogEvent.STANDARD_ERROR 10 | import org.gradle.api.tasks.testing.logging.TestLogEvent.STANDARD_OUT 11 | import org.gradle.kotlin.dsl.configure 12 | import org.gradle.kotlin.dsl.withType 13 | import org.jetbrains.dokka.gradle.DokkaTask 14 | import org.jetbrains.kotlin.gradle.dsl.JvmTarget 15 | import org.jetbrains.kotlin.gradle.targets.js.dsl.ExperimentalWasmDsl 16 | 17 | plugins { 18 | alias(libs.plugins.kotlin) 19 | alias(libs.plugins.spotless) 20 | alias(libs.plugins.kotest.multiplatform) 21 | alias(libs.plugins.detekt) 22 | alias(libs.plugins.dokka) 23 | alias(libs.plugins.kover) 24 | alias(libs.plugins.kotlinx.serialization) 25 | alias(libs.plugins.publish) 26 | alias(libs.plugins.knit) 27 | } 28 | 29 | repositories { 30 | mavenCentral() 31 | } 32 | 33 | spotless { 34 | kotlin { 35 | ktfmt().kotlinlangStyle().configure { 36 | it.setBlockIndent(2) 37 | it.setContinuationIndent(2) 38 | it.setRemoveUnusedImports(true) 39 | it.setManageTrailingCommas(true) 40 | } 41 | } 42 | } 43 | 44 | java { 45 | sourceCompatibility = VERSION_11 46 | targetCompatibility = VERSION_11 47 | } 48 | 49 | tasks { 50 | withType().configureEach { 51 | this.compilerOptions.jvmTarget.set(JvmTarget.JVM_11) 52 | } 53 | 54 | withType().configureEach { 55 | maxParallelForks = Runtime.getRuntime().availableProcessors() 56 | useJUnitPlatform() 57 | testLogging { 58 | exceptionFormat = TestExceptionFormat.FULL 59 | events = setOf(SKIPPED, FAILED, STANDARD_OUT, STANDARD_ERROR) 60 | } 61 | useJUnitPlatform() 62 | } 63 | } 64 | 65 | kotlin { 66 | explicitApi() 67 | 68 | jvm() 69 | js(IR) { 70 | browser() 71 | nodejs() 72 | } 73 | 74 | @OptIn(ExperimentalWasmDsl::class) 75 | wasmJs { 76 | browser() 77 | nodejs() 78 | d8() 79 | } 80 | linuxX64() 81 | macosX64() 82 | macosArm64() 83 | iosSimulatorArm64() 84 | iosX64() 85 | linuxArm64() 86 | watchosSimulatorArm64() 87 | watchosX64() 88 | watchosArm32() 89 | watchosArm64() 90 | tvosSimulatorArm64() 91 | tvosX64() 92 | tvosArm64() 93 | iosArm64() 94 | mingwX64() 95 | 96 | sourceSets { 97 | commonMain { 98 | dependencies { 99 | implementation(kotlin("stdlib")) 100 | api(libs.arrow.optics) 101 | api(libs.kotlinx.serialization.json) 102 | } 103 | } 104 | 105 | commonTest { 106 | dependencies { 107 | implementation(libs.kotest.frameworkEngine) 108 | implementation(libs.kotest.assertionsCore) 109 | implementation(libs.kotest.property) 110 | } 111 | } 112 | 113 | named("jvmTest") { 114 | dependencies { 115 | implementation(libs.kotest.runnerJUnit5) 116 | implementation(libs.kotlinx.knit.test) 117 | } 118 | } 119 | } 120 | } 121 | 122 | configure { 123 | siteRoot = "https://nomisrev.github.io/kotlinx-serialization-jsonpath/" 124 | } 125 | 126 | configure { 127 | parallel = true 128 | buildUponDefaultConfig = true 129 | allRules = true 130 | } 131 | 132 | tasks { 133 | withType().configureEach { 134 | outputDirectory.set(rootDir.resolve("docs")) 135 | moduleName.set("KotlinX Serialization JsonPath") 136 | dokkaSourceSets { 137 | named("commonMain") { 138 | includes.from("README.md") 139 | perPackageOption { 140 | matchingRegex.set(".*\\.internal.*") 141 | suppress.set(true) 142 | } 143 | externalDocumentationLink("https://kotlinlang.org/api/kotlinx.serialization/") 144 | sourceLink { 145 | localDirectory.set(file("src/commonMain/kotlin")) 146 | remoteUrl.set(uri("https://github.com/nomisRev/kotlinx-serialization-jsonpath/tree/main/src/commonMain/kotlin").toURL()) 147 | remoteLineSuffix.set("#L") 148 | } 149 | } 150 | } 151 | } 152 | 153 | getByName("knitPrepare").dependsOn(getTasksByName("dokka", true)) 154 | 155 | withType().configureEach { 156 | reports { 157 | html.required.set(true) 158 | sarif.required.set(true) 159 | txt.required.set(false) 160 | xml.required.set(false) 161 | } 162 | 163 | exclude("**/example/**") 164 | exclude("**/ReadMeSpec.kt") 165 | } 166 | 167 | configureEach { 168 | if (name == "build") dependsOn(withType()) 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=1g 2 | kotlin.code.style=official 3 | 4 | GROUP=io.github.nomisrev 5 | SONATYPE_HOST=S01 6 | RELEASE_SIGNING_ENABLED=true 7 | 8 | POM_ARTIFACT_ID=kotlinx-serialization-jsonpath 9 | POM_NAME=Kotlinx Serialization JsonPath 10 | POM_DESCRIPTION=JsonPath offers a simple DSL to work with JsonElement from Kotlinx Serialization Json, this allows you to easily work with JSON in Kotlin in a typed manner. 11 | POM_URL=https://github.com/nomisrev/kotlinx-serialization-jsonpath/ 12 | 13 | POM_LICENSE_NAME=The Apache Software License, Version 2.0 14 | POM_LICENSE_URL=https://www.apache.org/licenses/LICENSE-2.0.txt 15 | POM_LICENSE_DIST=repo 16 | 17 | POM_SCM_URL=https://github.com/nomisrev/kotlinx-serialization-jsonpath/ 18 | POM_SCM_CONNECTION=scm:git:git://github.com/nomisRev/kotlinx-serialization-jsonpath.git 19 | POM_SCM_DEV_CONNECTION=scm:git:ssh://git@github.com/nomisRev/kotlinx-serialization-jsonpath.git 20 | 21 | POM_DEVELOPER_ID=nomisRev 22 | POM_DEVELOPER_NAME=Simon Vergauwen 23 | POM_DEVELOPER_URL=https://github.com/nomisRev/ 24 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/nomisRev/kotlinx-serialization-jsonpath/ebc3a97cd92b461b9f93c2b639ef80f86c97cd5d/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.12.1-bin.zip 4 | networkTimeout=10000 5 | validateDistributionUrl=true 6 | zipStoreBase=GRADLE_USER_HOME 7 | zipStorePath=wrapper/dists 8 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | # This is normally unused 84 | # shellcheck disable=SC2034 85 | APP_BASE_NAME=${0##*/} 86 | # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) 87 | APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit 88 | 89 | # Use the maximum available, or set MAX_FD != -1 to use that value. 90 | MAX_FD=maximum 91 | 92 | warn () { 93 | echo "$*" 94 | } >&2 95 | 96 | die () { 97 | echo 98 | echo "$*" 99 | echo 100 | exit 1 101 | } >&2 102 | 103 | # OS specific support (must be 'true' or 'false'). 104 | cygwin=false 105 | msys=false 106 | darwin=false 107 | nonstop=false 108 | case "$( uname )" in #( 109 | CYGWIN* ) cygwin=true ;; #( 110 | Darwin* ) darwin=true ;; #( 111 | MSYS* | MINGW* ) msys=true ;; #( 112 | NONSTOP* ) nonstop=true ;; 113 | esac 114 | 115 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 116 | 117 | 118 | # Determine the Java command to use to start the JVM. 119 | if [ -n "$JAVA_HOME" ] ; then 120 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 121 | # IBM's JDK on AIX uses strange locations for the executables 122 | JAVACMD=$JAVA_HOME/jre/sh/java 123 | else 124 | JAVACMD=$JAVA_HOME/bin/java 125 | fi 126 | if [ ! -x "$JAVACMD" ] ; then 127 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 128 | 129 | Please set the JAVA_HOME variable in your environment to match the 130 | location of your Java installation." 131 | fi 132 | else 133 | JAVACMD=java 134 | if ! command -v java >/dev/null 2>&1 135 | then 136 | die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | fi 142 | 143 | # Increase the maximum file descriptors if we can. 144 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 145 | case $MAX_FD in #( 146 | max*) 147 | # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. 148 | # shellcheck disable=SC2039,SC3045 149 | MAX_FD=$( ulimit -H -n ) || 150 | warn "Could not query maximum file descriptor limit" 151 | esac 152 | case $MAX_FD in #( 153 | '' | soft) :;; #( 154 | *) 155 | # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. 156 | # shellcheck disable=SC2039,SC3045 157 | ulimit -n "$MAX_FD" || 158 | warn "Could not set maximum file descriptor limit to $MAX_FD" 159 | esac 160 | fi 161 | 162 | # Collect all arguments for the java command, stacking in reverse order: 163 | # * args from the command line 164 | # * the main class name 165 | # * -classpath 166 | # * -D...appname settings 167 | # * --module-path (only if needed) 168 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 169 | 170 | # For Cygwin or MSYS, switch paths to Windows format before running java 171 | if "$cygwin" || "$msys" ; then 172 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 173 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 174 | 175 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 176 | 177 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 178 | for arg do 179 | if 180 | case $arg in #( 181 | -*) false ;; # don't mess with options #( 182 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 183 | [ -e "$t" ] ;; #( 184 | *) false ;; 185 | esac 186 | then 187 | arg=$( cygpath --path --ignore --mixed "$arg" ) 188 | fi 189 | # Roll the args list around exactly as many times as the number of 190 | # args, so each arg winds up back in the position where it started, but 191 | # possibly modified. 192 | # 193 | # NB: a `for` loop captures its iteration list before it begins, so 194 | # changing the positional parameters here affects neither the number of 195 | # iterations, nor the values presented in `arg`. 196 | shift # remove old arg 197 | set -- "$@" "$arg" # push replacement arg 198 | done 199 | fi 200 | 201 | 202 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 203 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 204 | 205 | # Collect all arguments for the java command: 206 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, 207 | # and any embedded shellness will be escaped. 208 | # * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be 209 | # treated as '${Hostname}' itself on the command line. 210 | 211 | set -- \ 212 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 213 | -classpath "$CLASSPATH" \ 214 | org.gradle.wrapper.GradleWrapperMain \ 215 | "$@" 216 | 217 | # Stop when "xargs" is not available. 218 | if ! command -v xargs >/dev/null 2>&1 219 | then 220 | die "xargs is not available" 221 | fi 222 | 223 | # Use "xargs" to parse quoted args. 224 | # 225 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 226 | # 227 | # In Bash we could simply go: 228 | # 229 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 230 | # set -- "${ARGS[@]}" "$@" 231 | # 232 | # but POSIX shell has neither arrays nor command substitution, so instead we 233 | # post-process each arg (as a line of input to sed) to backslash-escape any 234 | # character that might be a shell metacharacter, then use eval to reverse 235 | # that process (while maintaining the separation between arguments), and wrap 236 | # the whole thing up as a single "set" statement. 237 | # 238 | # This will of course break if any of these variables contains a newline or 239 | # an unmatched quote. 240 | # 241 | 242 | eval "set -- $( 243 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 244 | xargs -n1 | 245 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 246 | tr '\n' ' ' 247 | )" '"$@"' 248 | 249 | exec "$JAVACMD" "$@" 250 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | @rem This is normally unused 30 | set APP_BASE_NAME=%~n0 31 | set APP_HOME=%DIRNAME% 32 | 33 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 34 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 35 | 36 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 37 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 38 | 39 | @rem Find java.exe 40 | if defined JAVA_HOME goto findJavaFromJavaHome 41 | 42 | set JAVA_EXE=java.exe 43 | %JAVA_EXE% -version >NUL 2>&1 44 | if %ERRORLEVEL% equ 0 goto execute 45 | 46 | echo. 1>&2 47 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 48 | echo. 1>&2 49 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 50 | echo location of your Java installation. 1>&2 51 | 52 | goto fail 53 | 54 | :findJavaFromJavaHome 55 | set JAVA_HOME=%JAVA_HOME:"=% 56 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 57 | 58 | if exist "%JAVA_EXE%" goto execute 59 | 60 | echo. 1>&2 61 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 62 | echo. 1>&2 63 | echo Please set the JAVA_HOME variable in your environment to match the 1>&2 64 | echo location of your Java installation. 1>&2 65 | 66 | goto fail 67 | 68 | :execute 69 | @rem Setup the command line 70 | 71 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 72 | 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if %ERRORLEVEL% equ 0 goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | set EXIT_CODE=%ERRORLEVEL% 85 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 86 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 87 | exit /b %EXIT_CODE% 88 | 89 | :mainEnd 90 | if "%OS%"=="Windows_NT" endlocal 91 | 92 | :omega 93 | -------------------------------------------------------------------------------- /knit.code.include: -------------------------------------------------------------------------------- 1 | // This file was automatically generated from ${file.name} by Knit tool. Do not edit. 2 | @file:Suppress("InvalidPackageDeclaration") 3 | package ${knit.package}.${knit.name} 4 | 5 | import kotlinx.serialization.* 6 | import kotlinx.serialization.json.* 7 | import arrow.optics.* 8 | import io.github.nomisrev.* 9 | import arrow.optics.typeclasses.* 10 | 11 | private const val JSON_STRING = """ 12 | { 13 | "name": "Arrow", 14 | "address": { 15 | "city": "Functional Town", 16 | "street": { 17 | "number": 1337, 18 | "name": "Functional street" 19 | } 20 | }, 21 | "employees": [ 22 | { 23 | "name": "John", 24 | "lastName": "doe" 25 | }, 26 | { 27 | "name": "Jane", 28 | "lastName": "doe" 29 | } 30 | ] 31 | }""" -------------------------------------------------------------------------------- /knit.properties: -------------------------------------------------------------------------------- 1 | knit.dir=src/jvmTest/kotlin/example/ 2 | knit.package=com.example 3 | 4 | test.dir=src/jvmTest/kotlin/ 5 | test.package=com.example.test 6 | 7 | knit.include=knit.code.include 8 | test.template=knit.test.template 9 | -------------------------------------------------------------------------------- /knit.test.template: -------------------------------------------------------------------------------- 1 | // This file was automatically generated from ${file.name} by Knit tool. Do not edit. 2 | @file:Suppress("MaxLineLength", "InvalidPackageDeclaration") 3 | 4 | package ${test.package} 5 | 6 | import io.kotest.core.spec.style.StringSpec 7 | import kotlinx.knit.test.* 8 | 9 | class ${test.name} : StringSpec({ 10 | <#list cases as case><#assign method = test["mode.${case.param}"]!"custom"> 11 | "${case.name}" { 12 | captureOutput("${case.name}") { ${case.knit.package}.${case.knit.name}.main() }<#if method != "custom">.${method}( 13 | <#list case.lines as line> 14 | "${line?j_string}"<#sep>, 15 | 16 | ) 17 | <#else>.also { lines -> 18 | check(${case.param}) 19 | } 20 | 21 | } 22 | <#sep> 23 | 24 | 25 | }) -------------------------------------------------------------------------------- /libs.versions.toml: -------------------------------------------------------------------------------- 1 | [versions] 2 | arrow = "2.0.1" 3 | dokka = "2.0.0" 4 | kotlin = "2.1.10" 5 | kotest = "6.0.0.M2" 6 | kover = "0.9.1" 7 | detekt = "1.23.8" 8 | kotest-arrow="2.0.0" 9 | kotlinx-json="1.8.0" 10 | kotlinx-knit="0.5.0" 11 | publish="0.30.0" 12 | knit="0.5.0" 13 | spotless="7.0.2" 14 | 15 | [libraries] 16 | arrow-optics = { module = "io.arrow-kt:arrow-optics", version.ref = "arrow" } 17 | dokka-core = { module = "org.jetbrains.dokka:dokka-core", version.ref = "dokka" } 18 | kotest-assertionsCore = { module = "io.kotest:kotest-assertions-core", version.ref = "kotest" } 19 | kotest-frameworkEngine = { module = "io.kotest:kotest-framework-engine", version.ref = "kotest" } 20 | kotest-property = { module = "io.kotest:kotest-property", version.ref = "kotest" } 21 | kotest-runnerJUnit5 = { module = "io.kotest:kotest-runner-junit5", version.ref = "kotest" } 22 | kotest-arrow = { module = "io.kotest.extensions:kotest-assertions-arrow", version.ref = "kotest-arrow" } 23 | kotlin-gradle = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin" } 24 | detekt-gradle = { module = "io.gitlab.arturbosch.detekt:detekt-gradle-plugin", version.ref = "detekt" } 25 | kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinx-json" } 26 | kotlinx-knit-test = { module = "org.jetbrains.kotlinx:kotlinx-knit-test", version.ref = "kotlinx-knit" } 27 | 28 | [plugins] 29 | kotlin = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" } 30 | dokka = { id = "org.jetbrains.dokka", version.ref = "dokka" } 31 | kover = { id = "org.jetbrains.kotlinx.kover", version.ref = "kover" } 32 | kotest-multiplatform = { id = "io.kotest.multiplatform", version.ref = "kotest" } 33 | kotlin-multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" } 34 | detekt = { id = "io.gitlab.arturbosch.detekt", version.ref = "detekt" } 35 | kotlinx-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } 36 | publish = { id = "com.vanniktech.maven.publish", version.ref="publish" } 37 | knit = { id = "org.jetbrains.kotlinx.knit", version.ref="knit" } 38 | spotless = { id = "com.diffplug.spotless", version.ref ="spotless" } -------------------------------------------------------------------------------- /renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "config:base" 4 | ], 5 | "commitBodyTable": true, 6 | "packageRules": [ 7 | { 8 | "matchPackagePatterns": [ 9 | "*" 10 | ], 11 | "matchUpdateTypes": [ 12 | "major", 13 | "minor", 14 | "patch" 15 | ], 16 | "groupName": "all dependencies", 17 | "groupSlug": "all" 18 | } 19 | ] 20 | } -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | rootProject.name = "kotlinx-serialization-jsonpath" 2 | 3 | pluginManagement { 4 | repositories { 5 | gradlePluginPortal() 6 | mavenCentral() 7 | } 8 | } 9 | 10 | dependencyResolutionManagement { 11 | versionCatalogs { 12 | create("libs") { 13 | from(files("libs.versions.toml")) 14 | } 15 | } 16 | 17 | repositories { 18 | mavenCentral() 19 | gradlePluginPortal() 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/commonMain/kotlin/io/github/nomisrev/JsonPath.kt: -------------------------------------------------------------------------------- 1 | @file:Suppress("TooManyFunctions") 2 | package io.github.nomisrev 3 | 4 | import arrow.core.Option 5 | import arrow.core.None 6 | import arrow.core.Some 7 | import arrow.optics.Optional 8 | import arrow.optics.Traversal 9 | import arrow.optics.typeclasses.At 10 | import arrow.optics.typeclasses.Index 11 | import arrow.optics.typeclasses.FilterIndex 12 | import kotlinx.serialization.KSerializer 13 | import kotlinx.serialization.json.Json 14 | import kotlinx.serialization.json.JsonElement 15 | import kotlinx.serialization.json.JsonNull 16 | import kotlinx.serialization.json.JsonObject 17 | import kotlinx.serialization.json.JsonArray 18 | import kotlinx.serialization.serializer 19 | 20 | /** 21 | * Starting point of the JsonPath DSL 22 | * This represents the _root_ of the path you want to define in your `JsonElement` 23 | */ 24 | public object JsonPath : Optional by Optional.id() 25 | 26 | /** Extract a [Boolean] value from a [JsonElement] */ 27 | public inline val Optional.boolean: Optional 28 | inline get() = this@boolean composeOptional Optional.jsonBoolean() 29 | 30 | /** Extract a [String] value from a [JsonElement] */ 31 | public inline val Optional.string: Optional 32 | inline get() = this composeOptional Optional.jsonString() 33 | 34 | /** Extract a [Double] value from a [JsonElement] */ 35 | public inline val Optional.double: Optional 36 | inline get() = this composeOptional Optional.jsonDouble() 37 | 38 | /** Extract a [Float] value from a [JsonElement] */ 39 | public inline val Optional.float: Optional 40 | inline get() = this composeOptional Optional.jsonFloat() 41 | 42 | /** Extract a [Long] value from a [JsonElement] */ 43 | public inline val Optional.long: Optional 44 | inline get() = this composeOptional Optional.jsonLong() 45 | 46 | /** Extract a [Int] value from a [JsonElement] */ 47 | public inline val Optional.int: Optional 48 | inline get() = this composeOptional Optional.jsonInt() 49 | 50 | /** Extract a [List] of [JsonElement] from a [JsonElement] */ 51 | public inline val Optional.array: Optional> 52 | inline get() = this composeOptional Optional.jsonArray() 53 | 54 | /** Extract a [Map] of [String] to [JsonElement] from a [JsonElement] */ 55 | @Suppress("TopLevelPropertyNaming") 56 | public inline val Optional.`object`: Optional> 57 | inline get() = this composeOptional Optional.jsonObject() 58 | 59 | /** Extract `null` from a [JsonElement] */ 60 | @Suppress("TopLevelPropertyNaming") 61 | public inline val Optional.`null`: Optional 62 | inline get() = this composeOptional Optional.jsonNull() 63 | 64 | /** Select _every_ entry in [JsonArray] and [JsonObject] */ 65 | public inline val Optional.every: Traversal 66 | inline get() = this compose Traversal.jsonElement() 67 | 68 | /** 69 | * Select value at [selector]. The following syntax is supported for [selector]: 70 | * - without square brackets: select the property with that name, 71 | * - `['field']`: select the property with that name, 72 | * - `[i]`, where `i` is a number: select the index in an array. 73 | */ 74 | public fun Optional.select( 75 | selector: String 76 | ): Optional { 77 | val inBrackets = matchNameInBrackets(selector) 78 | val ix = matchIndexInBrackets(selector) 79 | return when { 80 | inBrackets != null -> get(inBrackets) 81 | ix != null -> get(ix) 82 | else -> get(selector) 83 | } 84 | } 85 | 86 | /** 87 | * Select values at [selector]. The following syntax is supported for [selector]: 88 | * - without square brackets: select the property with that name, 89 | * - `['field']`: select the property with that name, 90 | * - `*`: select all the fields or indices, 91 | * - `[i]`, where `i` is a number: select the index in an array, 92 | * - `[i,j,...]` where `i,j,...` are numbers: select the indices in an array, 93 | * - `[start:end]`: select the indices from `start` to (but not including) `end`, 94 | * - `[start:]`: select the indices from `start` to the end of the array. 95 | */ 96 | public fun Optional.selectEvery( 97 | selector: String 98 | ): Traversal { 99 | val inBrackets = matchNameInBrackets(selector) 100 | val ixs = matchIndicesInBrackets(selector) 101 | val startIx = matchStartIndex(selector) 102 | val startEndIx = matchStartEndIndex(selector) 103 | return when { 104 | inBrackets != null -> get(inBrackets) 105 | selector == "*" -> this compose Traversal.jsonElement() // inline definition of [every] 106 | ixs != null -> filterIndex { it in ixs } 107 | startIx != null -> filterIndex { it >= startIx } 108 | startEndIx != null -> get(startEndIx.first until startEndIx.second) 109 | else -> get(selector) 110 | } 111 | } 112 | 113 | /** 114 | * Select _path_ with _dot (.) or bracket ([i]) notation_ 115 | * 116 | * ```kotlin 117 | * JsonPath.path("addresses[0].street.name") 118 | * ``` 119 | */ 120 | public fun Optional.path( 121 | path: String, 122 | fieldDelimiter: String = ".", 123 | indexDelimiter: String = "[" 124 | ): Optional = 125 | path.splitTwice(fieldDelimiter, indexDelimiter).fold(this) { acc, pathSelector -> acc.select(pathSelector) } 126 | 127 | /** 128 | * Select _path_ with multiple results, see [selectEvery] for the allowed selectors 129 | * 130 | * ```kotlin 131 | * JsonPath.path("addresses[0].*.street.name") 132 | * ``` 133 | */ 134 | public fun Optional.pathEvery( 135 | path: String, 136 | fieldDelimiter: String = ".", 137 | indexDelimiter: String = "[" 138 | ): Traversal = 139 | path.splitTwice(fieldDelimiter, indexDelimiter).fold(this) { 140 | acc: Traversal, pathSelector -> acc.selectEvery(pathSelector) 141 | } 142 | 143 | /** 144 | * Select a property with a [name] as an [Option]. 145 | * This allows you to erase the value by setting it to [None], 146 | * or allows you to overwrite it by setting a new [Some]. 147 | */ 148 | public fun Optional.at( 149 | name: String 150 | ): Optional> = 151 | `object` compose At.map().at(name) 152 | 153 | /** Select keys out of an [JsonObject] with the given [predicate] */ 154 | public fun Optional.filterKeys( 155 | predicate: (keys: String) -> Boolean 156 | ): Traversal = 157 | `object` compose FilterIndex.map().filter(predicate) 158 | 159 | /** Select a [property] out of a [JsonObject] */ 160 | public operator fun Optional.get( 161 | property: String 162 | ): Optional = 163 | `object` compose Index.map().index(property) 164 | 165 | /** Select an [index] out of a [JsonArray] */ 166 | public operator fun Optional.get( 167 | index: Int 168 | ): Optional = 169 | array compose Index.list().index(index) 170 | 171 | /** Select all indices from the [range] out of a [JsonArray] */ 172 | public operator fun Optional.get( 173 | range: ClosedRange 174 | ): Traversal = 175 | filterIndex { it in range } 176 | 177 | /** Select an indices out of a [JsonArray] with the given [predicate] */ 178 | public fun Optional.filterIndex( 179 | predicate: (index: Int) -> Boolean 180 | ): Traversal = 181 | array compose FilterIndex.list().filter(predicate) 182 | 183 | /** Extract a value of type [A] with an _implicit_ KotlinX Serializer */ 184 | public inline fun Optional.extract( 185 | parser: Json = Json.Default 186 | ): Optional = extract(serializer(), parser) 187 | 188 | /** Extract a value of type [A] given a [KSerializer] for [A] */ 189 | public fun Optional.extract( 190 | serializer: KSerializer, 191 | json: Json = Json.Default 192 | ): Optional = this composePrism parse(serializer, json) 193 | -------------------------------------------------------------------------------- /src/commonMain/kotlin/io/github/nomisrev/JsonPathEvery.kt: -------------------------------------------------------------------------------- 1 | @file:Suppress("TooManyFunctions") 2 | package io.github.nomisrev 3 | 4 | import arrow.core.None 5 | import arrow.core.Option 6 | import arrow.core.Some 7 | import arrow.optics.Traversal 8 | import arrow.optics.Optional 9 | import arrow.optics.typeclasses.At 10 | import arrow.optics.typeclasses.FilterIndex 11 | import arrow.optics.typeclasses.Index 12 | import kotlinx.serialization.KSerializer 13 | import kotlinx.serialization.json.Json 14 | import kotlinx.serialization.json.JsonArray 15 | import kotlinx.serialization.json.JsonElement 16 | import kotlinx.serialization.json.JsonNull 17 | import kotlinx.serialization.json.JsonObject 18 | import kotlinx.serialization.serializer 19 | 20 | /** Extract a [Boolean] value from a [JsonElement] */ 21 | public inline val Traversal.boolean: Traversal 22 | inline get() = this@boolean compose Optional.jsonBoolean() 23 | 24 | /** Extract a [String] value from a [JsonElement] */ 25 | public inline val Traversal.string: Traversal 26 | inline get() = this compose Optional.jsonString() 27 | 28 | /** Extract a [Double] value from a [JsonElement] */ 29 | public inline val Traversal.double: Traversal 30 | inline get() = this compose Optional.jsonDouble() 31 | 32 | /** Extract a [Float] value from a [JsonElement] */ 33 | public inline val Traversal.float: Traversal 34 | inline get() = this compose Optional.jsonFloat() 35 | 36 | /** Extract a [Long] value from a [JsonElement] */ 37 | public inline val Traversal.long: Traversal 38 | inline get() = this compose Optional.jsonLong() 39 | 40 | /** Extract a [Int] value from a [JsonElement] */ 41 | public inline val Traversal.int: Traversal 42 | inline get() = this compose Optional.jsonInt() 43 | 44 | /** Extract a [List] of [JsonElement] from a [JsonElement] */ 45 | public inline val Traversal.array: Traversal> 46 | inline get() = this compose Optional.jsonArray() 47 | 48 | /** Extract a [Map] of [String] to [JsonElement] from a [JsonElement] */ 49 | @Suppress("TopLevelPropertyNaming") 50 | public inline val Traversal.`object`: Traversal> 51 | inline get() = this compose Optional.jsonObject() 52 | 53 | /** Extract `null` from a [JsonElement] */ 54 | @Suppress("TopLevelPropertyNaming") 55 | public inline val Traversal.`null`: Traversal 56 | inline get() = this compose Optional.jsonNull() 57 | 58 | /** Select _every_ entry in [JsonArray] and [JsonObject] */ 59 | public inline val Traversal.every: Traversal 60 | inline get() = this compose Traversal.jsonElement() 61 | 62 | /** 63 | * Select value at [selector]. The following syntax is supported for [selector]: 64 | * - without square brackets: select the property with that name, 65 | * - `['field']`: select the property with that name, 66 | * - `[i]`, where `i` is a number: select the index in an array. 67 | */ 68 | public fun Traversal.select(selector: String): Traversal { 69 | val inBrackets = matchNameInBrackets(selector) 70 | val ix = matchIndexInBrackets(selector) 71 | return when { 72 | inBrackets != null -> get(inBrackets) 73 | ix != null -> get(ix) 74 | else -> get(selector) 75 | } 76 | } 77 | 78 | /** 79 | * Select values at [selector]. The following syntax is supported for [selector]: 80 | * - without square brackets: select the property with that name, 81 | * - `['field']`: select the property with that name, 82 | * - `*`: select all the fields or indices, 83 | * - `[i]`, where `i` is a number: select the index in an array, 84 | * - `[i,j,...]` where `i,j,...` are numbers: select the indices in an array, 85 | * - `[start:end]`: select the indices from `start` to (but not including) `end`, 86 | * - `[start:]`: select the indices from `start` to the end of the array. 87 | */ 88 | public fun Traversal.selectEvery( 89 | selector: String 90 | ): Traversal { 91 | val inBrackets = matchNameInBrackets(selector) 92 | val ixs = matchIndicesInBrackets(selector) 93 | val startIx = matchStartIndex(selector) 94 | val startEndIx = matchStartEndIndex(selector) 95 | return when { 96 | inBrackets != null -> get(inBrackets) 97 | selector == "*" -> this compose Traversal.jsonElement() // inline definition of [every] 98 | ixs != null -> filterIndex { it in ixs } 99 | startIx != null -> filterIndex { it >= startIx } 100 | startEndIx != null -> get(startEndIx.first until startEndIx.second) 101 | else -> get(selector) 102 | } 103 | } 104 | 105 | /** 106 | * Select _path_ with _dot (.) or bracket ([i]) notation_ 107 | * 108 | * ```kotlin 109 | * JsonPath.path("addresses[0].street.name") 110 | * ``` 111 | */ 112 | public fun Traversal.path( 113 | path: String, 114 | fieldDelimiter: String = ".", 115 | indexDelimiter: String = "[" 116 | ): Traversal = 117 | path.splitTwice(fieldDelimiter, indexDelimiter).fold(this) { acc, pathSelector -> acc.select(pathSelector) } 118 | 119 | /** 120 | * Select _path_ with multiple results, see [selectEvery] for the allowed selectors 121 | * 122 | * ```kotlin 123 | * JsonPath.path("addresses[0].*.street.name") 124 | * ``` 125 | */ 126 | public fun Traversal.pathEvery( 127 | path: String, 128 | fieldDelimiter: String = ".", 129 | indexDelimiter: String = "[" 130 | ): Traversal = 131 | path.splitTwice(fieldDelimiter, indexDelimiter).fold(this) { acc, pathSelector -> acc.selectEvery(pathSelector) } 132 | 133 | /** 134 | * Select a property with a [name] as an [Option]. 135 | * This allows you to erase the value by setting it to [None], 136 | * or allows you to overwrite it by setting a new [Some]. 137 | */ 138 | public fun Traversal.at( 139 | name: String 140 | ): Traversal> = 141 | `object` compose At.map().at(name) 142 | 143 | /** Select keys out of an [JsonObject] with the given [predicate] */ 144 | public fun Traversal.filterKeys( 145 | predicate: (keys: String) -> Boolean 146 | ): Traversal = 147 | `object` compose FilterIndex.map().filter(predicate) 148 | 149 | /** Select a [property] out of a [JsonObject] */ 150 | public operator fun Traversal.get(property: String): Traversal = 151 | `object` compose Index.map().index(property) 152 | 153 | /** Select an [index] out of a [JsonArray] */ 154 | public operator fun Traversal.get(index: Int): Traversal = 155 | array compose Index.list().index(index) 156 | 157 | /** Select all indices from the [range] out of a [JsonArray] */ 158 | public operator fun Traversal.get( 159 | range: ClosedRange 160 | ): Traversal = 161 | filterIndex { it in range } 162 | 163 | /** Select an indices out of a [JsonArray] with the given [predicate] */ 164 | public fun Traversal.filterIndex( 165 | predicate: (index: Int) -> Boolean 166 | ): Traversal = array compose FilterIndex.list().filter(predicate) 167 | 168 | /** Extract a value of type [A] with an _implicit_ KotlinX Serializer */ 169 | public inline fun Traversal.extract( 170 | parser: Json = Json 171 | ): Traversal = extract(serializer(), parser) 172 | 173 | /** Extract a value of type [A] given a [KSerializer] for [A] */ 174 | public fun Traversal.extract( 175 | serializer: KSerializer, 176 | parser: Json = Json 177 | ): Traversal = this compose parse(serializer, parser) 178 | -------------------------------------------------------------------------------- /src/commonMain/kotlin/io/github/nomisrev/optics.kt: -------------------------------------------------------------------------------- 1 | @file:Suppress("TooManyFunctions") 2 | 3 | package io.github.nomisrev 4 | 5 | import arrow.core.left 6 | import arrow.core.right 7 | import arrow.core.Option 8 | import arrow.core.toOption 9 | import arrow.core.Either 10 | import arrow.core.fold 11 | import arrow.optics.Prism 12 | import arrow.optics.Lens 13 | import arrow.optics.Optional 14 | import arrow.optics.POptional 15 | import arrow.optics.Traversal 16 | import arrow.optics.PTraversal 17 | import arrow.optics.typeclasses.At 18 | import arrow.optics.typeclasses.Index 19 | import kotlinx.serialization.KSerializer 20 | import kotlinx.serialization.SerializationException 21 | import kotlinx.serialization.json.Json 22 | import kotlinx.serialization.json.JsonArray 23 | import kotlinx.serialization.json.JsonElement 24 | import kotlinx.serialization.json.JsonNull 25 | import kotlinx.serialization.json.JsonObject 26 | import kotlinx.serialization.json.JsonPrimitive 27 | import kotlinx.serialization.json.contentOrNull 28 | import kotlinx.serialization.json.doubleOrNull 29 | import kotlinx.serialization.json.floatOrNull 30 | import kotlinx.serialization.json.intOrNull 31 | import kotlinx.serialization.json.longOrNull 32 | 33 | public fun POptional.Companion.jsonBoolean(): Optional = JsonElementToBoolean 34 | 35 | public fun POptional.Companion.jsonString(): Optional = JsonElementToString 36 | 37 | public fun POptional.Companion.jsonDouble(): Optional = JsonElementToDouble 38 | 39 | public fun POptional.Companion.jsonFloat(): Optional = JsonElementToFloat 40 | 41 | public fun POptional.Companion.jsonLong(): Optional = JsonElementToLong 42 | 43 | public fun POptional.Companion.jsonInt(): Optional = JsonElementToInt 44 | 45 | public fun POptional.Companion.jsonNull(): Optional = JsonElementToJsNull 46 | 47 | public fun POptional.Companion.jsonArray(): Optional> = 48 | JsonElementToJsonArray 49 | 50 | public fun PTraversal.Companion.jsonArray(): Traversal = JsArrayTraversal 51 | 52 | public fun Index.Companion.jsonArray(): Index = JsArrayIndex 53 | 54 | public fun POptional.Companion.jsonObject(): Optional> = 55 | JsonElementToJsonObject 56 | 57 | public fun PTraversal.Companion.jsonObject(): Traversal = JsonObjectTraversal 58 | 59 | public fun Index.Companion.jsonObject(): Index = JsonObjectIndex 60 | 61 | public fun At.Companion.jsonObject(): At> = JsonObjectAt 62 | 63 | public fun PTraversal.Companion.jsonElement(): Traversal = JsonElementTraversal 64 | 65 | private object JsonObjectIndex : Index { 66 | override fun index(i: String): Optional = 67 | Optional( 68 | getOrModify = { it[i]?.right() ?: it.left() }, 69 | set = { jsonObject, new -> 70 | JsonObject(jsonObject.mapValues { (key, original) -> if (key == i) new else original }) 71 | } 72 | ) 73 | } 74 | 75 | private object JsonObjectAt : At> { 76 | override fun at(i: String): Lens> = 77 | Lens( 78 | get = { it[i].toOption() }, 79 | set = { js, optJs -> optJs.fold({ JsonObject(js - i) }, { JsonObject(js + Pair(i, it)) }) } 80 | ) 81 | } 82 | 83 | private object JsonObjectTraversal : Traversal { 84 | override fun modify(source: JsonObject, map: (focus: JsonElement) -> JsonElement): JsonObject = 85 | JsonObject(source.mapValues { (_, focus) -> map(focus) }) 86 | 87 | override fun foldMap(initial: R, combine: (R, R) -> R, source: JsonObject, map: (focus: JsonElement) -> R): R = 88 | source.fold(initial) { acc, (_, focus) -> combine(acc, map(focus)) } 89 | } 90 | 91 | private object JsArrayTraversal : Traversal { 92 | override fun foldMap(initial: R, combine: (R, R) -> R, source: JsonArray, map: (focus: JsonElement) -> R): R = 93 | source.fold(initial) { acc, json -> combine(acc, map(json)) } 94 | 95 | override fun modify(source: JsonArray, map: (focus: JsonElement) -> JsonElement): JsonArray = 96 | JsonArray(source.map(map)) 97 | } 98 | 99 | private object JsArrayIndex : Index { 100 | override fun index(i: Int): Optional = 101 | Optional( 102 | getOrModify = { it.getOrNull(i)?.right() ?: it.left() }, 103 | set = { jsArr, new -> 104 | JsonArray(jsArr.mapIndexed { index, original -> if (index == i) new else original }) 105 | } 106 | ) 107 | } 108 | 109 | /** 110 | * Unsafe optic: needs some investigation because it is required to extract reasonable typed values 111 | * from Json. 112 | * https://github.com/circe/circe/blob/master/modules/optics/src/main/scala/io/circe/optics/JsonPath.scala#L152 113 | */ 114 | @PublishedApi 115 | internal fun parse( 116 | serializer: KSerializer, 117 | parser: Json = Json.Default 118 | ): Prism = 119 | Prism( 120 | getOrModify = { json -> 121 | @Suppress("SwallowedException") 122 | try { 123 | parser.decodeFromJsonElement(serializer, json).right() 124 | } catch (serialization: SerializationException) { 125 | json.left() 126 | } 127 | }, 128 | reverseGet = { parser.encodeToJsonElement(serializer, it) } 129 | ) 130 | 131 | private inline val JsonElement.jsonPrimitiveOrNull: JsonPrimitive? 132 | inline get() = this as? JsonPrimitive 133 | 134 | private object JsonElementToBoolean : Optional { 135 | override fun getOrModify(source: JsonElement): Either = 136 | source.jsonPrimitiveOrNull?.contentOrNull?.toBooleanStrictOrNull()?.right() ?: source.left() 137 | 138 | override fun set(source: JsonElement, focus: Boolean): JsonElement = 139 | if (source is JsonPrimitive && source.contentOrNull?.toBooleanStrictOrNull() != null) { 140 | JsonPrimitive(focus) 141 | } else source 142 | } 143 | 144 | private object JsonElementToString : Optional { 145 | override fun getOrModify(source: JsonElement): Either = 146 | source.jsonPrimitiveOrNull?.let { json -> 147 | if (json.isString) json.content.right() else json.left() 148 | } 149 | ?: source.left() 150 | 151 | override fun set(source: JsonElement, focus: String): JsonElement = 152 | if (source is JsonPrimitive && source.isString) JsonPrimitive(focus) else source 153 | } 154 | 155 | private object JsonElementToDouble : Optional { 156 | override fun getOrModify(source: JsonElement): Either = 157 | source.jsonPrimitiveOrNull?.doubleOrNull?.right() ?: source.left() 158 | 159 | override fun set(source: JsonElement, focus: Double): JsonElement = 160 | if (source is JsonPrimitive && source.doubleOrNull != null) { 161 | JsonPrimitive(focus) 162 | } else source 163 | } 164 | 165 | private object JsonElementToFloat : Optional { 166 | override fun getOrModify(source: JsonElement): Either = 167 | source.jsonPrimitiveOrNull?.floatOrNull?.right() ?: source.left() 168 | 169 | override fun set(source: JsonElement, focus: Float): JsonElement = 170 | if (source is JsonPrimitive && source.floatOrNull != null) { 171 | JsonPrimitive(focus) 172 | } else source 173 | } 174 | 175 | private object JsonElementToLong : Optional { 176 | override fun getOrModify(source: JsonElement): Either = 177 | source.jsonPrimitiveOrNull?.longOrNull?.right() ?: source.left() 178 | 179 | override fun set(source: JsonElement, focus: Long): JsonElement = 180 | if (source is JsonPrimitive && source.longOrNull != null) { 181 | JsonPrimitive(focus) 182 | } else source 183 | } 184 | 185 | private object JsonElementToInt : Optional { 186 | override fun getOrModify(source: JsonElement): Either = 187 | source.jsonPrimitiveOrNull?.intOrNull?.right() ?: source.left() 188 | 189 | override fun set(source: JsonElement, focus: Int): JsonElement = 190 | if (source is JsonPrimitive && source.intOrNull != null) { 191 | JsonPrimitive(focus) 192 | } else source 193 | } 194 | 195 | private object JsonElementToJsNull : Optional { 196 | override fun getOrModify(source: JsonElement): Either = 197 | (source as? JsonNull)?.right() ?: source.left() 198 | 199 | override fun set(source: JsonElement, focus: JsonNull): JsonElement = 200 | if (source is JsonNull) JsonNull else source 201 | } 202 | 203 | private object JsonElementToJsonArray : Optional> { 204 | override fun getOrModify(source: JsonElement): Either> = 205 | (source as? JsonArray)?.right() ?: source.left() 206 | 207 | override fun set(source: JsonElement, focus: List): JsonElement = 208 | (source as? JsonArray)?.let { JsonArray(focus) } ?: source 209 | } 210 | 211 | private object JsonElementToJsonObject : Optional> { 212 | override fun getOrModify(source: JsonElement): Either> = 213 | (source as? JsonObject)?.right() ?: source.left() 214 | 215 | override fun set(source: JsonElement, focus: Map): JsonElement = 216 | (source as? JsonObject)?.let { JsonObject(focus) } ?: source 217 | } 218 | 219 | private object JsonElementTraversal : Traversal { 220 | override fun foldMap(initial: R, combine: (R, R) -> R, source: JsonElement, map: (focus: JsonElement) -> R): R = 221 | when (source) { 222 | JsonNull -> map(JsonNull) 223 | is JsonObject -> 224 | source.fold(initial) { acc, (_, focus) -> combine(acc, map(focus)) } 225 | 226 | is JsonArray -> source.fold(initial) { acc, json -> combine(acc, map(json)) } 227 | is JsonPrimitive -> map(source) 228 | } 229 | 230 | override fun modify(source: JsonElement, map: (focus: JsonElement) -> JsonElement): JsonElement = 231 | when (source) { 232 | JsonNull -> JsonNull 233 | is JsonObject -> JsonObject(source.mapValues { (_, focus) -> map(focus) }) 234 | is JsonArray -> JsonArray(source.map(map)) 235 | is JsonPrimitive -> map(source) 236 | } 237 | } 238 | 239 | @PublishedApi 240 | internal infix fun Optional.composeOptional(other: Optional): Optional = 241 | this compose other 242 | 243 | @PublishedApi 244 | internal infix fun Optional.composePrism(other: Prism): Optional = 245 | this compose other 246 | -------------------------------------------------------------------------------- /src/commonMain/kotlin/io/github/nomisrev/selectUtils.kt: -------------------------------------------------------------------------------- 1 | package io.github.nomisrev 2 | 3 | /** 4 | * Splits a string given those delimiters. 5 | * [removedDelimiter] is removed after splitting, 6 | * whereas [keptDelimiter] is kept around. 7 | * 8 | * For example, if we split `this[0].thing` 9 | * we get back `listOf("this", "[0]", "thing")`. 10 | */ 11 | public fun String.splitTwice( 12 | removedDelimiter: String = ".", 13 | keptDelimiter: String = "[" 14 | ): List = 15 | split(removedDelimiter).flatMap { 16 | when { 17 | !it.contains('[') -> listOf(it) 18 | it.startsWith('[') -> 19 | // if it starts with '[', remove the first useless empty match 20 | it.split(keptDelimiter).drop(1).map { keptDelimiter + it } 21 | else -> { 22 | // we know there's a '[', and not at the beginning 23 | val (init, rest) = it.split(keptDelimiter, limit = 2) 24 | listOf(init) + rest.split(keptDelimiter).map { keptDelimiter + it } 25 | } 26 | } 27 | } 28 | 29 | // remember, group capture starts at 1, not at 0! 30 | public val MatchResult.firstMatch: String? 31 | get() = groupValues.getOrNull(1) 32 | 33 | public fun matchIndexInBrackets(selector: String): Int? = 34 | Regex("""\[([0-9]+)\]""").matchEntire(selector)?.firstMatch?.toInt() 35 | 36 | public fun matchIndicesInBrackets(selector: String): List? = 37 | Regex("""\[([0-9]+(,[0-9]+)*)\]""").matchEntire(selector)?.firstMatch?.let { 38 | it.split(',').map { it.toInt() } 39 | } 40 | 41 | public fun matchStartIndex(selector: String): Int? = 42 | Regex("""\[([0-9]+):\]""").matchEntire(selector)?.firstMatch?.toInt() 43 | 44 | public fun matchStartEndIndex(selector: String): Pair? = 45 | Regex("""\[([0-9]+):([0-9]+)\]""").matchEntire(selector)?.groupValues?.let { 46 | it[1].toInt() to it[2].toInt() 47 | } 48 | 49 | public fun matchNameInBrackets(selector: String): String? = 50 | Regex("""\['([^']*)'\]""").matchEntire(selector)?.firstMatch 51 | -------------------------------------------------------------------------------- /src/commonTest/kotlin/io/github/nomisrev/Arb.kt: -------------------------------------------------------------------------------- 1 | package io.github.nomisrev 2 | 3 | import io.kotest.property.Arb 4 | import io.kotest.property.arbitrary.boolean 5 | import io.kotest.property.arbitrary.choice 6 | import io.kotest.property.arbitrary.constant 7 | import io.kotest.property.arbitrary.double 8 | import io.kotest.property.arbitrary.filterNot 9 | import io.kotest.property.arbitrary.float 10 | import io.kotest.property.arbitrary.int 11 | import io.kotest.property.arbitrary.list 12 | import io.kotest.property.arbitrary.long 13 | import io.kotest.property.arbitrary.map 14 | import io.kotest.property.arbitrary.string 15 | import kotlinx.serialization.SerializationStrategy 16 | import kotlinx.serialization.json.Json 17 | import kotlinx.serialization.json.JsonArray 18 | import kotlinx.serialization.json.JsonElement 19 | import kotlinx.serialization.json.JsonNull 20 | import kotlinx.serialization.json.JsonObject 21 | import kotlinx.serialization.json.JsonPrimitive 22 | import kotlinx.serialization.serializer 23 | 24 | fun Arb.Companion.street(): Arb = 25 | Arb.string().map(::Street) 26 | 27 | fun Arb.Companion.city(): Arb = 28 | Arb.list(street()).map(::City) 29 | 30 | fun Arb.Companion.jsInt(): Arb = 31 | int().map(::JsonPrimitive) 32 | 33 | fun Arb.Companion.jsLong(): Arb = 34 | long().map(::JsonPrimitive) 35 | 36 | fun Arb.Companion.jsFloat(): Arb = 37 | float().filterNot(Float::isNaN).map(::JsonPrimitive) 38 | 39 | fun Arb.Companion.jsDouble(): Arb = 40 | double().filterNot(Double::isNaN).map(::JsonPrimitive) 41 | 42 | fun Arb.Companion.jsString(): Arb = 43 | Arb.string().map(::JsonPrimitive) 44 | 45 | fun Arb.Companion.jsBoolean(): Arb = 46 | boolean().map(::JsonPrimitive) 47 | 48 | fun Arb.Companion.jsNull(): Arb = 49 | constant(JsonNull) 50 | 51 | private fun genJson(): Arb = 52 | Arb.choice(Arb.jsInt(), Arb.jsLong(), Arb.jsDouble(), Arb.jsString(), Arb.jsNull()) 53 | 54 | fun Arb.Companion.jsArray(): Arb = 55 | list(genJson()).map(::JsonArray) 56 | 57 | fun Arb.Companion.jsArray(valid: Arb, EN: SerializationStrategy): Arb = 58 | list(valid).map { list -> JsonArray(list.map { elem -> Json.encodeToJsonElement(EN, elem) }) } 59 | 60 | inline fun Arb.Companion.jsArray(valid: Arb): Arb = 61 | jsArray(valid, serializer()) 62 | 63 | fun Arb.Companion.jsObject(): Arb = 64 | map(Arb.string(), genJson()).map(::JsonObject) 65 | 66 | fun Arb.Companion.json(valid: Arb, EN: SerializationStrategy): Arb = 67 | valid.map { Json.encodeToJsonElement(EN, it) } 68 | 69 | inline fun Arb.Companion.json(valid: Arb): Arb = 70 | json(valid, serializer()) 71 | 72 | fun Arb.Companion.json(): Arb = choice( 73 | Arb.jsInt(), 74 | Arb.jsLong(), 75 | Arb.jsDouble(), 76 | Arb.jsString(), 77 | Arb.jsNull(), 78 | Arb.jsArray(), 79 | Arb.jsObject(), 80 | ) 81 | -------------------------------------------------------------------------------- /src/commonTest/kotlin/io/github/nomisrev/JsonDSLSpec.kt: -------------------------------------------------------------------------------- 1 | package io.github.nomisrev 2 | 3 | import io.kotest.core.spec.style.StringSpec 4 | import io.kotest.matchers.nulls.shouldBeNull 5 | import io.kotest.matchers.shouldBe 6 | import io.kotest.property.Arb 7 | import io.kotest.property.checkAll 8 | import kotlinx.serialization.Serializable 9 | import kotlinx.serialization.json.Json 10 | import kotlinx.serialization.json.JsonObject 11 | import kotlinx.serialization.json.JsonPrimitive 12 | import kotlinx.serialization.json.boolean 13 | import kotlinx.serialization.json.float 14 | import kotlinx.serialization.json.int 15 | import kotlinx.serialization.json.long 16 | 17 | @Serializable 18 | data class City(val streets: List) 19 | 20 | @Serializable 21 | data class Street(val name: String) 22 | 23 | class JsonDSLSpec : StringSpec({ 24 | 25 | "bool prism" { 26 | checkAll(Arb.jsBoolean()) { jsBool -> 27 | JsonPath.boolean.getOrNull(jsBool) shouldBe jsBool.boolean 28 | } 29 | 30 | JsonPath.boolean.getOrNull(JsonPrimitive("text")).shouldBeNull() 31 | } 32 | 33 | "string prism" { 34 | checkAll(Arb.jsString()) { jsString -> 35 | JsonPath.string.getOrNull(jsString) shouldBe jsString.content 36 | } 37 | 38 | JsonPath.string.getOrNull(JsonPrimitive(false)).shouldBeNull() 39 | } 40 | 41 | "long prism" { 42 | checkAll(Arb.jsLong()) { jsLong -> 43 | JsonPath.long.getOrNull(jsLong) shouldBe jsLong.long 44 | } 45 | 46 | JsonPath.long.getOrNull(JsonPrimitive(false)).shouldBeNull() 47 | } 48 | 49 | "float prism" { 50 | checkAll(Arb.jsFloat()) { jsFloat -> 51 | JsonPath.float.getOrNull(jsFloat) shouldBe jsFloat.float 52 | } 53 | 54 | JsonPath.float.getOrNull(JsonPrimitive(false)).shouldBeNull() 55 | } 56 | 57 | "int prism" { 58 | checkAll(Arb.jsInt()) { jsInt -> 59 | JsonPath.int.getOrNull(jsInt) shouldBe jsInt.int 60 | } 61 | 62 | JsonPath.int.getOrNull(JsonPrimitive("text")).shouldBeNull() 63 | } 64 | 65 | "array prism" { 66 | checkAll(Arb.jsArray()) { jsArray -> 67 | JsonPath.array.getOrNull(jsArray) shouldBe jsArray 68 | } 69 | 70 | JsonPath.array.getOrNull(JsonPrimitive("5")).shouldBeNull() 71 | } 72 | 73 | "object prism" { 74 | checkAll(Arb.jsObject()) { jsObj -> 75 | JsonPath.`object`.getOrNull(jsObj) shouldBe jsObj 76 | } 77 | 78 | JsonPath.`object`.getOrNull(JsonPrimitive("5")).shouldBeNull() 79 | } 80 | 81 | "null prism" { 82 | checkAll(Arb.jsNull()) { jsNull -> 83 | JsonPath.`null`.getOrNull(jsNull) shouldBe jsNull 84 | } 85 | 86 | JsonPath.`null`.getOrNull(JsonPrimitive("5")).shouldBeNull() 87 | } 88 | 89 | "at from object" { 90 | checkAll(Arb.json(Arb.city())) { cityJson -> 91 | JsonPath.at("streets").getOrNull(cityJson)?.getOrNull() shouldBe (cityJson as? JsonObject)?.get("streets") 92 | } 93 | } 94 | 95 | "select from object" { 96 | checkAll(Arb.json(Arb.city())) { cityJson -> 97 | JsonPath.select("streets").getOrNull(cityJson) shouldBe (cityJson as? JsonObject)?.get("streets") 98 | } 99 | } 100 | 101 | "extract from object" { 102 | checkAll(Arb.json(Arb.city())) { cityJson -> 103 | JsonPath.extract(City.serializer()) 104 | .getOrNull(cityJson) shouldBe Json.decodeFromJsonElement(City.serializer(), cityJson) 105 | } 106 | } 107 | 108 | "get from array, using select and get" { 109 | checkAll(Arb.json(Arb.city())) { cityJson -> 110 | JsonPath.select("streets")[0] 111 | .extract(Street.serializer()) 112 | .getOrNull(cityJson) shouldBe Json.decodeFromJsonElement(City.serializer(), cityJson).streets.getOrNull(0) 113 | } 114 | } 115 | 116 | "get from array, using get" { 117 | checkAll(Arb.json(Arb.city())) { cityJson -> 118 | JsonPath["streets"][0]["name"].string 119 | .getOrNull(cityJson) shouldBe Json.decodeFromJsonElement(City.serializer(), cityJson).streets.getOrNull(0)?.name 120 | } 121 | } 122 | 123 | "get from array, using get range" { 124 | checkAll(Arb.json(Arb.city())) { cityJson -> 125 | JsonPath["streets"][0..0]["name"].string 126 | .getAll(cityJson) 127 | .getOrNull(0) shouldBe Json.decodeFromJsonElement(City.serializer(), cityJson).streets.getOrNull(0)?.name 128 | } 129 | } 130 | 131 | "get from array, using select with special syntax" { 132 | checkAll(Arb.json(Arb.city())) { cityJson -> 133 | JsonPath.select("['streets']").select("[0]") 134 | .extract(Street.serializer()) 135 | .getOrNull(cityJson) shouldBe Json.decodeFromJsonElement(City.serializer(), cityJson).streets.getOrNull(0) 136 | } 137 | } 138 | 139 | "get from array, using path" { 140 | checkAll(Arb.json(Arb.city())) { cityJson -> 141 | JsonPath.path("streets[0]") 142 | .extract(Street.serializer()) 143 | .getOrNull(cityJson) shouldBe Json.decodeFromJsonElement(City.serializer(), cityJson).streets.getOrNull(0) 144 | } 145 | } 146 | 147 | "get all elements from array" { 148 | checkAll(Arb.json(Arb.city())) { cityJson -> 149 | JsonPath.select("streets").selectEvery("*").select("name") 150 | .string 151 | .getAll(cityJson) shouldBe Json.decodeFromJsonElement(City.serializer(), cityJson).streets.map { it.name } 152 | } 153 | } 154 | 155 | "get all elements from array, using path" { 156 | checkAll(Arb.json(Arb.city())) { cityJson -> 157 | JsonPath.pathEvery("streets.*.name") 158 | .string 159 | .getAll(cityJson) shouldBe Json.decodeFromJsonElement(City.serializer(), cityJson).streets.map { it.name } 160 | } 161 | } 162 | }) 163 | -------------------------------------------------------------------------------- /src/commonTest/kotlin/io/github/nomisrev/KotestConfig.kt: -------------------------------------------------------------------------------- 1 | package io.github.nomisrev 2 | 3 | import io.kotest.core.config.AbstractProjectConfig 4 | import io.kotest.core.test.TestCaseOrder 5 | import io.kotest.property.PropertyTesting 6 | import kotlin.time.Duration 7 | import kotlin.time.Duration.Companion.seconds 8 | 9 | object KotestConfig : AbstractProjectConfig() { 10 | init { 11 | PropertyTesting.defaultIterationCount = 50 12 | } 13 | 14 | override val timeout: Duration = 15 | 30.seconds 16 | 17 | override val testCaseOrder: TestCaseOrder = 18 | TestCaseOrder.Random 19 | 20 | } 21 | -------------------------------------------------------------------------------- /src/jvmTest/kotlin/ReadMeSpec.kt: -------------------------------------------------------------------------------- 1 | // This file was automatically generated from README.md by Knit tool. Do not edit. 2 | @file:Suppress("MaxLineLength", "InvalidPackageDeclaration") 3 | 4 | package com.example.test 5 | 6 | import io.kotest.core.spec.style.StringSpec 7 | import kotlinx.knit.test.* 8 | 9 | class ReadMeSpec : StringSpec({ 10 | "ExampleReadme01" { 11 | captureOutput("ExampleReadme01") { com.example.exampleReadme01.main() }.verifyOutputLines( 12 | "{\"name\":\"ARROW\",\"address\":{\"city\":\"Functional Town\",\"street\":{\"number\":1337,\"name\":\"Functional street\"}},\"employees\":[{\"name\":\"John\",\"lastName\":\"doe\"},{\"name\":\"Jane\",\"lastName\":\"doe\"}]}" 13 | ) 14 | } 15 | 16 | "ExampleReadme02" { 17 | captureOutput("ExampleReadme02") { com.example.exampleReadme02.main() }.verifyOutputLines( 18 | "{\"name\":\"Arrow\",\"address\":{\"city\":\"Functional Town\",\"street\":{\"number\":1337,\"name\":\"FUNCTIONAL STREET\"}},\"employees\":[{\"name\":\"John\",\"lastName\":\"doe\"},{\"name\":\"Jane\",\"lastName\":\"doe\"}]}", 19 | "FUNCTIONAL STREET" 20 | ) 21 | } 22 | 23 | "ExampleReadme03" { 24 | captureOutput("ExampleReadme03") { com.example.exampleReadme03.main() }.verifyOutputLines( 25 | "{\"name\":\"Arrow\",\"address\":{\"city\":\"Functional Town\",\"street\":{\"number\":1337,\"name\":\"Functional street\"}},\"employees\":[{\"name\":\"JOHN\",\"lastName\":\"doe\"},{\"name\":\"JANE\",\"lastName\":\"doe\"}]}", 26 | "[JOHN, JANE]" 27 | ) 28 | } 29 | }) 30 | -------------------------------------------------------------------------------- /src/jvmTest/kotlin/example/example-readme-01.kt: -------------------------------------------------------------------------------- 1 | // This file was automatically generated from README.md by Knit tool. Do not edit. 2 | @file:Suppress("InvalidPackageDeclaration") 3 | package com.example.exampleReadme01 4 | 5 | import kotlinx.serialization.* 6 | import kotlinx.serialization.json.* 7 | import arrow.optics.* 8 | import io.github.nomisrev.* 9 | import arrow.optics.typeclasses.* 10 | 11 | private const val JSON_STRING = """ 12 | { 13 | "name": "Arrow", 14 | "address": { 15 | "city": "Functional Town", 16 | "street": { 17 | "number": 1337, 18 | "name": "Functional street" 19 | } 20 | }, 21 | "employees": [ 22 | { 23 | "name": "John", 24 | "lastName": "doe" 25 | }, 26 | { 27 | "name": "Jane", 28 | "lastName": "doe" 29 | } 30 | ] 31 | }""" 32 | 33 | fun main(): Unit { 34 | 35 | val json: JsonElement = Json.decodeFromString(JSON_STRING) 36 | val name: Optional = JsonPath.select("name").string 37 | println(name.modify(json, String::uppercase)) 38 | } 39 | -------------------------------------------------------------------------------- /src/jvmTest/kotlin/example/example-readme-02.kt: -------------------------------------------------------------------------------- 1 | // This file was automatically generated from README.md by Knit tool. Do not edit. 2 | @file:Suppress("InvalidPackageDeclaration") 3 | package com.example.exampleReadme02 4 | 5 | import kotlinx.serialization.* 6 | import kotlinx.serialization.json.* 7 | import arrow.optics.* 8 | import io.github.nomisrev.* 9 | import arrow.optics.typeclasses.* 10 | 11 | private const val JSON_STRING = """ 12 | { 13 | "name": "Arrow", 14 | "address": { 15 | "city": "Functional Town", 16 | "street": { 17 | "number": 1337, 18 | "name": "Functional street" 19 | } 20 | }, 21 | "employees": [ 22 | { 23 | "name": "John", 24 | "lastName": "doe" 25 | }, 26 | { 27 | "name": "Jane", 28 | "lastName": "doe" 29 | } 30 | ] 31 | }""" 32 | 33 | fun main(): Unit { 34 | 35 | val json: JsonElement = Json.decodeFromString(JSON_STRING) 36 | val name: Optional = JsonPath.path("address.street.name").string 37 | val res: JsonElement = name.modify(json, String::uppercase).also(::println) 38 | name.getOrNull(res)?.also(::println) 39 | } 40 | -------------------------------------------------------------------------------- /src/jvmTest/kotlin/example/example-readme-03.kt: -------------------------------------------------------------------------------- 1 | // This file was automatically generated from README.md by Knit tool. Do not edit. 2 | @file:Suppress("InvalidPackageDeclaration") 3 | package com.example.exampleReadme03 4 | 5 | import kotlinx.serialization.* 6 | import kotlinx.serialization.json.* 7 | import arrow.optics.* 8 | import io.github.nomisrev.* 9 | import arrow.optics.typeclasses.* 10 | 11 | private const val JSON_STRING = """ 12 | { 13 | "name": "Arrow", 14 | "address": { 15 | "city": "Functional Town", 16 | "street": { 17 | "number": 1337, 18 | "name": "Functional street" 19 | } 20 | }, 21 | "employees": [ 22 | { 23 | "name": "John", 24 | "lastName": "doe" 25 | }, 26 | { 27 | "name": "Jane", 28 | "lastName": "doe" 29 | } 30 | ] 31 | }""" 32 | 33 | fun main(): Unit { 34 | 35 | val json: JsonElement = Json.decodeFromString(JSON_STRING) 36 | val employeesName: Traversal = JsonPath.select("employees").every.select("name").string 37 | val res: JsonElement = employeesName.modify(json, String::uppercase).also(::println) 38 | employeesName.getAll(res).also(::println) 39 | } 40 | -------------------------------------------------------------------------------- /src/jvmTest/kotlin/example/example-readme-04.kt: -------------------------------------------------------------------------------- 1 | // This file was automatically generated from README.md by Knit tool. Do not edit. 2 | @file:Suppress("InvalidPackageDeclaration") 3 | package com.example.exampleReadme04 4 | 5 | import kotlinx.serialization.* 6 | import kotlinx.serialization.json.* 7 | import arrow.optics.* 8 | import io.github.nomisrev.* 9 | import arrow.optics.typeclasses.* 10 | 11 | private const val JSON_STRING = """ 12 | { 13 | "name": "Arrow", 14 | "address": { 15 | "city": "Functional Town", 16 | "street": { 17 | "number": 1337, 18 | "name": "Functional street" 19 | } 20 | }, 21 | "employees": [ 22 | { 23 | "name": "John", 24 | "lastName": "doe" 25 | }, 26 | { 27 | "name": "Jane", 28 | "lastName": "doe" 29 | } 30 | ] 31 | }""" 32 | 33 | fun main(): Unit { 34 | 35 | val json: JsonElement = Json.decodeFromString(JSON_STRING) 36 | val employeesName: Traversal = JsonPath.pathEvery("employees.*.name").string 37 | val res: JsonElement = employeesName.modify(json, String::uppercase).also(::println) 38 | employeesName.getAll(res).also(::println) 39 | } 40 | --------------------------------------------------------------------------------