12 ms·
How to Use JSON Path
- eknkc 2y agoI've used postgresql's jsonpath support to create user defined filtering rules on db rows. It made things a lot easier than whatever other methods I could come up with.
- porsager 2y agoThat sounds very interesting. Could you elaborate on that?
- wodenokoto 2y agoIs there a general name for the kind of data structure JSON represents? We see this kind of Nete’s data all over the place (json, yaml, python dictionaries, toml, etc, etc) and I’m thinking wouldn’t it be nice if we had a path language that worked across these structures, just like how we can regex any strings? So we can have a pathql executable that we can feed yaml and json data to, but I can reuse the query in Python when I want to extract values from a json stream I just deserialized.
- lucianbr 2y agoIs it anything else than a tree with properties for each node? I think you could well apply jsonpath to yaml, except for the different data types, which is what makes you need xmlpath, jsonpath, file path, css and so on. If you're willing to do some automagic conversions, you could probably do that right now, if you write the code for it.
- exceptione 2y agoA tree with properties indeed. They vary in syntax and how they deal with scalars, objects and collections. Having to write 'myKey' is a bit unfortunate in json for example. Still, for any document larger than 20 lines yaml will fall apart easily. Xml (dialects) mark the beginning and end of nodes explicitly, which deviates from json/yaml. Xml can represent nodes within the value, which is impossible for json/yaml. To convert such xml value to the latter, you have to break up such a node in fragments and represent them as a collection in json/yaml.
- tsimionescu 2y ago> Xml can represent nodes within the value, which is impossible for json/yaml. To convert such xml value to the latter, you have to break up such a node in fragments and represent them as a collection in json/yaml. Are you talking about XML like `<text>Something something <para> inside </para> something else</text>`? I thought this would also presented as the text element having three children, the text "Something something", the <para> tag with its subtree, and the text "something else". Am I misremembering?
- exceptione 2y agoExactly, that is the «breaking apart» I was talking about. Xml is the more natural way for humans to express that particular use case.
- tsimionescu 2y agoBut my point is that an XML parser would still present that as three children, right? It's just when writing the document that you get the advantage, the data model is the same.
- exceptione 2y agoJup, it is human ergonomics, but a mismatch for your average programming data structure. I think that is one reason why json took of for exchanging machine readable data, xml is too expressive, and leans towards document authoring.
- tsimionescu 2y agoAgreed, a lot of the features that make XML very nice for embedding tags in text documents make it very inefficient at expressing explicit tree data structures.
- rileymat2 2y agoI doubt that, if I had my money on it I’d guess the main reason is var obj=JSON.parse(string) and its ease.
- PurpleRamen 2y agoThe complicated part is, that this tree has different types of nodes. Some support properties and child's, some not. So I would call it a chimera tree or mixed tree, or something like that.
- lucianbr 2y agoFor a query language, you can generalize to all nodes supporting all things. You will be able to write some queries that will never return results, at least in a given input data format. That does not seem so bad.
- hughesjj 2y agoNo it makes so much more sense to introduce nil and then constantly pepper your code with ? (Null-colasecing) Operators everywhere (Looking at you, jq, though to be fair JSON itself supports null...)
- int_19h 2y agoCoincidentally, this is exactly what XPath and XQuery do. E.g. text nodes don't have children nor attributes, yet it is perfectly legal to do text()/foo or text()/@foo - and the result is an empty sequence. If you want this kind of semantics with JSON, take a look at https://www.jsoniq.org https://www.jsoniq.org
- crabmusket 2y agoI feel like `fq` has a query path language that's kind of generic across lots of file types. It can be fairly verbose for that reason. I was using it to debug MsgPack documents and it was a lot less intuitive than just using some dotted string paths with `jq`. https://github.com/wader/fq/ https://github.com/wader/fq/
- wwader 2y agoHey, fq author here. Happy to hear it's useful! could you elaborate a bit more how it was less intuitive? fq's query language is jq with some small additions so i wonder if you might mean the decoded structure is more detailed/verbose as it includes all the "low level" details? maybe your looking for the "torepr" function that converts the detailed structure into the "represented" value?
- ranger_danger 2y agoNever seen this tool before but it looks quite handy. Thanks!
- wwader 2y agohope it can be of use!
- crabmusket 2y agoYes that's exactly what I meant, the MsgPack documents had quite a detailed structure. torepr didn't quite work for me as I was dealing with objects containing large binary blobs and it was awkward. fq is a great tool and I shouldn't have suggested this was a problem unique to it! I think this kind of "issue" is inevitable when dealing with so many types of input. And to be honest I struggle hard using jq as well for anything other than very basic paths, due to infrequent usage.
- wwader 2y agoI see, thanks for replying and no worries! yeap some of the "self-describing" formats like msgpack, cbor etc will because of how fq works have to be decoded into something more of a meta-msgpack etc. About blobs, if you want to change how (possibly large) binaries are represented as JSON you can use the bits_format options, see https://github.com/wader/fq/blob/master/doc/usage.md#options https://github.com/wader/fq/blob/master/doc/usage.md#options, so fq -o bits_format=md5 torepr ... I can highly recommend to learn jq, it's what makes fq really useful, and as a bonus you will learn jq in general! :)
- itronitron 2y agoYou could say it is 'object-oriented' since the ON stands for Object Notation.
- sesm 2y ago'Nested maps and arrays of strings, numbers and booleans'? I propose the name AMofBNS :)
- deleted 2y ago[deleted]
- froh 2y agonested records and arrays?
- qazxcvbnm 2y agoAs to cross format path querying, I see limited value in such an endeavour; the reason that one deals with such formats is generally because it is used as an interface to configure some tool, but moving across different tools, besides the path queries, even the configuration schemas differ, and having a cross format converter would do you no good. The fact that many such configuration formats support subtly (or drastically) divergent types of objects does this idea no good either. Speaking of this topic, I would be very interested in a CLI tool that translated between different dialects of regex. As opposed to general data or configuration, I find the case for cross format conversion very compelling for regexes; the objects that different regex languages deal with are functionally completely identical. I would be very happy to be able to craft a regex to search for something in vim, then convert the regex to grep or use another tool on the shell, then perhaps adapt it to some other scripting languages e.g. Javascript/Ruby/Perl. Indeed I am sad that I am not finding any CLI tools (non web-based) for this beyond https://github.com/Anadian/regex-translator https://github.com/Anadian/regex-translator . Am hopeful for more suggestions.
- PurpleRamen 2y agoI think one popular name, independent of the format, is to call them documents. Or more specifically, the type of database which use them often runs under that term. Maybe specify it as data-document to not confuse it with freeform office-documents. But one problem is, that each format has slightly different ways it works. Some have nodes which support properties, some not. This makes building a proper query-language a bit more complicated if it should not end up ugly.
- lucianbr 2y agoWhat's the problem with nodes supporting or not some properties? For querying you can treat all nodes as supporting all things, and the user just needs to write a query that acutually works, which is what they would need to do anyway. Yes, if you want to make the query language reject as incorrect queries that specify a property on a node that can't have properties, it is messy. But is this really necessary? You can write faulty queries anyway. And it's not a programming language for complex systems, where it really helps to prevent mistakes early. SQL works fine with no type safety and so on.
- PurpleRamen 2y agoThe problem is that you can't easily reuse a query with different formats, with a swallow designed language. You will still end up writing format-targeted queries, which then open the question of why you would even bother in the first place using a watered down language, instead of a format-optimized one.
- jkaptur 2y agoAnother issue is that the term "document" is also used to refer to XML or HTML.
- PurpleRamen 2y agoXML is for data-exchange, competing with JSON and others. So I have no problem putting it to the data-documents, even though it's more a frankenstein. But HTML is an office-document, used for freetext, nobody really should use it for data, even though sometimes it's used that way.
- layer8 2y agoTree-structured data
- irgolic 2y agoThe general name is semi-structured data, as opposed to structured data (tables) and unstructured data (free text).
- emmelaich 2y agohttps://augeas.net/ https://augeas.net/
- TachyonicBytes 2y agoThe Readings in Database Systems book calls it "general purpose hierarchical data format" at some point, which seems the most fitting name for me. You generally don't see yaml or XML be called that, but there's some information on the net that you can find about it.
- err4nt 2y agoStructually, it's a tree. JSON cannot include circularity (like JavaScript objects can) so it's either an object, or nested objects.
- specialist 2y agogrove - tree decorated w/ key-value pairs. eg JSON, XML w/o text nodes object graph - grove plus object references. eg serialization formats knowledge graph - object graph where parent-child relations are explicit, using subject-verb-object clauses. like how Java Spring "flattens" object graphs. document - grove plus random text nodes
- zzo38computer 2y agoAlthough there are similar data structures, not all of them are supersets nor subsets of the data structures of JSON. For example, some data types that JSON lacks are: - Integers (including 64-bit integers and longer) - Non-finite floating point (Infinity, NaN) - Keys of types other than strings - Non-Unicode strings (e.g. byte sequences, TRON code, etc) - Date/time - Links Additionally, they may differ of whether or not the order of keys should be retained.
- pydry 2y agoThese types of languages are a bad idea, just as XPath was. They are complex enough to be a maintenance/bug risk AND don't bring any additional benefit to just writing code in your normal programming language to do the same thing. You can take my list comprehensions from my cold, dead hands. There isn't a use case I've seen where these types of mini languages fit well. Ostensibly, you could give it to a user to write to query JSON in a domain-agnostic way in an app but I think it would just confuse most users as well as not being powerful enough for half of their use cases. Sometimes it's better just to write code.
- Adiqq 2y ago> don't bring any additional benefit to just writing code in your normal programming language to do the same thing. In some cases advantage is that you don't create new code and you just use some relatively standard tool. You just fetch some public package that handles various edge cases and you just prepare script that describes what you want to do with some program. This is useful, if you work in containerized environment and configuration exists as json or yaml. Often I just use jq or yq, instead of reinventing wheel to just read or write some values.
- Drakim 2y agoI agree, it gives the same vibe as wanting to somehow bring back the simplicity of excel formulas rather than having to write normal code, to revive that dream of convenient one-liners. But there is a reason excel has a ceiling of maintainability that always turns it into a spaghetti mess once it's big enough.
- Silphendio 2y agoJSON Path: $.store.book[?@.price < 10].title Python: [x['title'] for x in data['store']['book'] if x['price'] < 10] Javascript: data.store.book.filter(x=>x.price < 10).map(x=>x.title)
- fmbb 2y agoThat javascript version is obviously objectively the best alternative.
- xnorswap 2y agoI look forward to the inevitable JSON path injection attacks given how widespread XPATH injection used to be. ( See https://owasp.org/www-community/attacks/XPATH_Injection https://owasp.org/www-community/attacks/XPATH_Injection for more info. )
- gonzo41 2y agoYep. Yep, Yep. You have to wonder why we can't just leave nice things alone.
- pwdisswordfishc 2y agoOnly as inevitable as the dearth of interpolation/parametrized query primitives… though whether the industry has actually learnt the bitter lessons of SQL injection remains to be seen. I don’t hold my hopes up too much.
- pydry 2y agoYou can just bypass the injection risk entirely by hardcoding the values as this example demonstrates: https://news.ycombinator.com/item?id=40246089 https://news.ycombinator.com/item?id=40246089 (I'm being sarcastic, obviously. You are 100% right)
- wmil 2y agoThis first came out in 2007 without picking up much popularity, so I wouldn't worry about it becoming widespread.
- philstu 2y agoThe standard was developed because its being used by so many people in so many ways with so many different implementations that a standard was required to align them all, so im not sure the "nobody is really using it" argument holds much weight.
- jawns 2y agoOne of the best tools I've found for manipulating JSON via JsonPath syntax is https://jsonata.org https://jsonata.org In addition to simple queries that allow you to select one (or multiple) matching nodes, it also provides some helper functions, such as arithmetic, comparisons, sorting, grouping, datetime manipulation, and aggregation (e.g. sum, max, min). It's written in JS and can be used in Node or in the browser, and there's also a Python wrapper: https://pypi.org/project/pyjsonata/ https://pypi.org/project/pyjsonata/
- replwoacause 2y agoLooks awesome, can't wait to try it out on my side project.
- ashconnor 2y agoIs it using JsonPath? This looks more intuitive to me.
- snthpy 2y agoThanks for this! The 5-min intro really undersells it as that part is not that much better than JSONPath. I started watching the London Node User Group video next and was about to switch it off but decided to hang on a bit longer because I busy with something anyway. Then it finally started getting into its real differentiators: constructing new objects and reductions. I even had to click around the documentation link three times until I figured out how to get to the real docs. It's a really well thought out query language that is actually Turing complete. I really want to try it out on some real data in anger to see how well it holds up in practice. I'm also thinking about what could be taken over into PRQL which I'm somewhat involved in.
- dherikb 2y agoInsomnia and Bruno has a feature to filter the responses using JSON Path. It's really useful.
- justin_oaks 2y agoI never noticed that small bar at the bottom of the response section in Bruno. That IS very useful. Thanks for the tip.
- thinkmassive 2y agokubectl has JSON Path support built in, it’s very useful https://kubernetes.io/docs/reference/kubectl/jsonpath/ https://kubernetes.io/docs/reference/kubectl/jsonpath/
- itslennysfault 2y agoAAH-HA... That's why this felt familiar to me. I haven't used K8 in over a year now, but I used this all the time at my previous job. Didn't know it was "JSON Path" just knew it as something I used in kubectl often.
- Tade0 2y agoI've used JSONPath in a small side project that was supposed to be a linter for TypeScript with JSONPath querying over the abstract.syntax tree: https://github.com/Tade0/permit-a38/tree/master https://github.com/Tade0/permit-a38/tree/master Ultimately the linting rules proved to be easier to write than read.
- jeremiahbuckley 2y ago1. Create a mock json document that has the structure you are trying to query. 2. Ask [newest LLM] to write the proper json path to get to the element you want to reach.
- TachyonicBytes 2y agoSeems easier to create a program where you can click the element and it shows the jsonpath itself
- jeremiahbuckley 2y agoThere’s nothing thing wrong with that approach if you’re working with jsonpaths on the regular. It’s all about time management, I guess. With json, and xml, and probably yaml, there is this recurring long-term pattern of: 1. Creat tree-structure document format that is flexible enough to handle all use cases. 2. Write a ton of content in this format. 3. Have to figure out a query pattern to accurately retrieve good info out of these structures. Generally, I feel we’ve become good at querying normalized table data. But—-and maybe it’s just me being stupid—-wending through tree-structured data is still tricky. And I recently discovered LLMs are great at solving for it, if you ask clearly.
- TachyonicBytes 2y agoThe thing about querying tree-structured data being currently humanly harder than tabular data rings true to me, I always struggle with some very simple tree-sitter queries.
- sxg 2y agoThis is exactly the type of thing that LLMs are very good at generating and explaining for you. I've done this countless times to create and understand regex patterns.
- jgalt212 2y agoIs the necessity of tools like JSON Path really just an indication that APIs are increasingly returning too much junk and / or way more data than the client actually requested and / or needs? In dev mode, our internal APIs return pretty printed JSON so one can inspect via view-source, more, or text editor.
- Manfred 2y agoNot necessarily. JSON is used in a lot of places, also for large documents in data lakes and archives. It's useful to be able to query them with tools.
- tylerneylon 2y agoNot sure if this is a common problem, but I built a tool to help me quickly understand the main schema, and where most of the data is, for a new JSON file given to me. It makes the assumption that sometimes peer elements in a list will have the same structure (eg they'll be objects with similar sets of keys). If that's true, it learns the structure of the file, prints out the heaviest _aggregated_ path (meaning it thinks in terms of a directory-like structure), as well as giving you various size-per-path hints to help introduce yourself to the JSON file: https://github.com/tylerneylon/json_profile https://github.com/tylerneylon/json_profile
- crashabr 2y agoLooks quite useful, thanks! Though when you said that the tool helps you understand the main schema, I thought it would output an outline of the json tree. But it doesn't seem to do that, unless there's an option for it?
- andrewingram 2y agoWe're using JSONPath to annotate parts of JSON fields in PostgreSQL that need to be extracted/replaced for localization. Whilst I'd naturally prefer we didn't store display copy in these structures, it was a fun thing to implement. Contrived example: @localizedModel({ title: {}, quiz: { jsonPath: '$.[question,answerMd]' }, }) class MyQuiz { title: string; quiz: JSONObject; }
- avi_vallarapu 2y agothere is possibly a need for more unified standard across different implementations particularly from a software development and API design perspective. During parsing and manipulation of JSON data, the syntactical discrepancies/behaviours between various libraries might need a common specification, for interoperability. features like type-aware queries or schema validation, may be very helpful.
- Powdering7082 2y agoI am kind of surprised that they don't mention jq at all, it seems like a similar tool that is fairly wide spread.
- riquito 2y agoWell, the article is about JSONPath and jq doesn't use it
- turadg 2y agoSame. I was curious what the differences are. JSONPath can only pull data out, like XPath. jq can do much more, like perform transformations. jq is also more concise: .book[0].title versus JSONPath: $..book[0].title Here's a discussion with more comparisons: https://github.com/serverlessworkflow/specification/issues/216 https://github.com/serverlessworkflow/specification/issues/2...
- philstu 2y agojq is wonderful but not relevant to the discussion. This is about using JSONPath for OpenAPI Overlays and automated API Style Guides like Spectral. You cannot use jq for either of those things. Notbing against jq, just a different discussion.
- swah 2y agoAlternative: use jless and copy the path of the thing you want, then (maybe) generailze
- philstu 2y agoThat wouldn't help anyone working with OpenAPI Overlays or Spectral which is what this article is about.
- throwaway413 2y agoHas anyone had performance issues using JSONPath? We are processing large pieces of data per request in a node express service and we believe JSONPath is causing our service to lock up and slow down. We’ve seen the issue improve as we have started refactoring out JSONPath usage for vanilla iteration and conditional checks. There are a lot of factors at play so we can’t quite put our thumb on JSONPath, but it’s the current suspect and curious if others have run into anything similar.
- philstu 2y agoIt would depend far more on the implementation than the concept/spec of JSONPath itself. What implementation are you using?
- simonw 2y agoSQLite includes a subset of JSON Path in the core database these days, used by functions like json_extract() I wrote up my own detailed notes on that subset a while ago: https://til.simonwillison.net/sqlite/json-extract-path https://til.simonwillison.net/sqlite/json-extract-path
- err4nt 2y agoIn the past I've used XPath, and CSS selectors using this library to filter and find data in JSON: https://github.com/tomhodgins/espath https://github.com/tomhodgins/espath The approach is to take the JavaScript object, convert it to XML DOM, run the query (either using standard XPath, or standard CSS selectors) and then either convert the DOM back into objects, or another way I've seen it done is to keep a register of the original objects and retrieve the original objects. In this way, JSON, and any JavaScript object with non-circularity can be sifted and searched and filtered in reliable ways using already-standardized methods just by using those technologies together in a fun new way. There is not necessarily a need for inventing a new custom syntax/DSL for querying unless you don't want to make use of CSS and XPath, or have very specific needs.
- billbrown 2y agoIf you're on a Mac, OK JSON is a tremendous aid in working with documents and includes a decent JSONPath query dialog. (Very happy user) https://okjson.app/ https://okjson.app/
- user3939382 2y agoI wish there weren’t so many JSON path syntaxes. I’m comfortable with jq, then there’s JSON path, I forget which one AWS CLI is using, MySQL has their own. It’s impossible for me to get muscle memory with any of them.
- thecosmicfrog 2y agoAWS CLI uses JMESPath.
- deepakarora3 2y agoJSONPath is good when it comes to querying large JSON documents. But in my opinion, more than this is the need to simplify reading and writing from JSON documents. We use POJOs / model classes which can become a chore for large JSON documents. While it is possible to read paths, I had not seen any tool using which we could read and write JSON paths in a document without using POJOs. And so I wrote unify-jdocs - read and write any JSON path with a single line of code without ever using POJOs. And also use model documents to replace JSONSchema. You can find this library here -> https://github.com/americanexpress/unify-jdocs https://github.com/americanexpress/unify-jdocs.