Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing json and searching through it

Tags:

I have this code

import json from pprint import pprint json_data=open('bookmarks.json') jdata = json.load(json_data) pprint (jdata) json_data.close() 

How can I search through it for u'uri': u'http:?

like image 403
BKovac Avatar asked Dec 05 '11 09:12

BKovac


People also ask

Is JSON searchable?

JSON Data is Easy to Search Full-text search engine applications are also natural for JSON databases and are made possible through another type of index.

How do you parse JSON?

parse() JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON. parse() , as the Javascript standard specifies.

What is JSON parsing example?

JSON (JavaScript Object Notation) is a straightforward data exchange format to interchange the server's data, and it is a better alternative for XML. This is because JSON is a lightweight and structured language.


1 Answers

ObjectPath is a library that provides ability to query JSON and nested structures of dicts and lists. For example, you can search for all attributes called "foo" regardless how deep they are by using $..foo.

While the documentation focuses on the command line interface, you can perform the queries programmatically by using the package's Python internals. The example below assumes you've already loaded the data into Python data structures (dicts & lists). If you're starting with a JSON file or string you just need to use load or loads from the json module first.

import objectpath  data = [     {'foo': 1, 'bar': 'a'},     {'foo': 2, 'bar': 'b'},     {'NoFooHere': 2, 'bar': 'c'},     {'foo': 3, 'bar': 'd'}, ]  tree_obj = objectpath.Tree(data)  tuple(tree_obj.execute('$..foo')) # returns: (1, 2, 3) 

Notice that it just skipped elements that lacked a "foo" attribute, such as the third item in the list. You can also do much more complex queries, which makes ObjectPath handy for deeply nested structures (e.g. finding where x has y that has z: $.x.y.z). I refer you to the documentation and tutorial for more information.

like image 141
Scott H Avatar answered Oct 25 '22 14:10

Scott H