Reputation: 1787
I have multiple JSON file who have all the same schema:
{"q0":{"query":"William","limit":3}}
{"q1":{"query":"Joe","limit":3}}
Using xpath or JSONPath I would like to extract each element into a table:
|id | query |limit |
|q0 | William | 3 |
|q1 | Joe | 3 |
I have no problem getting the query and limit field using ..query
and ..limit
but I can'a find the syntax to extract the id
field (ie q0
and q1
).
I've been trying @*
and $*
with no success.
So is there a way to select a JSON element which have no node name?
As said in the comment, I am using talend tExtractJSONField component which use XPath to parse JSON.
Upvotes: 3
Views: 3924
Reputation: 1122
Acutally, you can use XPath on your JSON structure using DefiantJS. This library extends the global object JSON with the method "search" - with which you can query JSON structure with XPath. The method returns the matches as an array.
var data = [
{
"q0": {
"query": "William",
"limit": 3
}
},
{
"q1": {
"query": "Joe",
"limit": 1
}
},
{
"q1": {
"query": "Bill",
"limit": 2
}
}
],
found_1 = JSON.search(data, "//*[limit=3]"),
found_2 = JSON.search(data, "//*[limit>1]");
document.getElementById('output_1').innerHTML = found_1[0].query;
document.getElementById('output_2').innerHTML = found_2[0].length;
To see this in action, check out this fiddle; http://jsfiddle.net/hbi99/zWU6x/
Also, check out the XPath Evaluator here to see and test XPath queries; http://defiantjs.com/#xpath_evaluator
Upvotes: 0
Reputation: 6218
Using .
you can get the current element. There is no possibility using JsonPath to extract key names. Hence, you can do this in JavaScript by using for
and grabbing the key name.
The following HTML shows a complete example:
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="jsonpath.js"></script>
</head>
<body>
<h1 id="h1"></h1>
<script type="text/javascript">
var o = {"q0":{"query":"WilLIAM","limit":3}};
var key;
for(var i in jsonPath(o, ".")[0]) key = i;
document.getElementById("h1").appendChild(document.createTextNode(
key
));
</script>
</body>
</html>
Here is a Plunkr: http://plnkr.co/edit/CaZD1lVhr1E2S8VN5vnP
Upvotes: 2
Reputation: 3818
By using Google's Gson library you can read as below.
HashMap<String, JsonElement> myMap = new Gson().fromJson(jsonString, new TypeToken<HashMap<String, JsonElement>>(){}.getType());
String id = null, query = null;
int limit = 0;
for (Entry<String, JsonElement> entry : myMap.entrySet()) {
id = entry.getKey();
if(entry.getValue() != null) {
JsonElement je = entry.getValue();
if(je.isJsonObject()) {
JsonObject jo = je.getAsJsonObject();
query = jo.get("query").getAsString();
limit = jo.get("limit").getAsInt();
}
}
}
print("id : " + id + " query : " + query + " limit : " + limit);
Upvotes: 0
Reputation: 568
The documentation at http://goessner.net/articles/JsonPath/ would point to $.q0
.
Upvotes: 0