Using http://www.aspjson.com/ or https://github.com/nagaozen/asp-xtreme-evolution/blob/master/lib/axe/classes/Parsers/json2.asp object I managed to get my data from URL to the dictionary object. But I tried and can not think of the way to get the data from the "opening" object using aspjson :-( I have not managed to find a way to get any data using json2.asp library. Here is my data:
{
"restaurant": {
"id": 6,
"email": "xyz#gmail.com",
"visiblemail": "1",
"date": "2014-07-24 07:38:59",
"logo": "818_294.png",
"img": "818_554|818_558|818_563",
"opening": {
"sun": [
"closed"
],
"mon": [
"10.00",
"20.00"
],
"tue": [
"10.00",
"20.00"
],
"wed": [
"10.00",
"20.00"
],
"thu": [
"10.00",
"20.00"
],
"fri": [
"10.00",
"20.00"
],
"sat": [
"closed"
],
"hol": [
"zaprto"
]
},
"timetable": null
}
}
I know both libraries use dictionary object to store the data, but I am lost how do I retrieve the data from the object.
You can use the isObject check to see if the element has inner members.
The include file used is from the link you gave
<!--#include file="aspJSON1.17.asp" -->
<%
Set oJSON = New aspJSON
jsonstring = "{ "&_
"""restaurant"": {"&_
"""id"": 6,"&_
"""email"": ""xyz#gmail.com"","&_
"""visiblemail"": ""1"","&_
"""date"": ""2014-07-24 07:38:59"","&_
"""logo"": ""818_294.png"","&_
"""img"": ""818_554|818_558|818_563"","&_
"""opening"": {"&_
" ""sun"": ["&_
" ""closed"""&_
" ],"&_
" ""mon"": ["&_
" ""10.00"","&_
" ""20.00"""&_
" ],"&_
" ""tue"": ["&_
" ""10.00"","&_
" ""20.00"""&_
" ],"&_
" ""wed"": ["&_
" ""10.00"","&_
" ""20.00"""&_
" ],"&_
" ""thu"": ["&_
" ""10.00"","&_
" ""20.00"""&_
" ],"&_
" ""fri"": ["&_
" ""10.00"","&_
" ""20.00"""&_
" ],"&_
" ""sat"": ["&_
" ""closed"""&_
" ],"&_
" ""hol"": ["&_
" ""zaprto"""&_
" ]"&_
"},"&_
"""timetable"": null"&_
"}"
'Load JSON string
oJSON.loadJSON(jsonstring)
set restaurant = oJSON.data("restaurant")
for each itm in restaurant
if Not IsObject(restaurant.item(itm)) then
Response.write itm &" : "& restaurant.item(itm) & "<br/>"
else
'opening
for each dayy in restaurant.item(itm)
Response.write dayy & ":"
Response.write restaurant.item(itm)(dayy)(0)
If restaurant.item(itm)(dayy)(1) <> "" Then
Response.write " - "
Response.write restaurant.item(itm)(dayy)(1)
End If
Response.write "<br/>"
next
end if
next
%>
Using the file at:https://github.com/nagaozen/asp-xtreme-evolution/blob/master/lib/axe/classes/Parsers/json2.asp
You can traverse through the json using the .enumerate() call, which returns all keys in a name-value collection and indexes in an array.
<%
Sub Traverse(oJson)
Dim key
For Each key In oJson.enumerate()
If IsObject(oJson.get(key)) Then
Response.write key & " => "
Traverse oJson.get(key) 'Recursive call
Else
Response.Write(key & "=" & oJson.get(key) & "<br/>")
End If
Next
End Sub
%>
Call it like:
set oJSON= json.parse(jsonstring)
Traverse oJSON
I have the json schema:
{
"type ": "record ",
"name ": "JSONSchema",
"namespace ": "com.jsonschema ",
"fields ": [{
"name ": "schema ",
"type ": "string "
},
{
"name ": "body ",
"type ": {
"type ": "record ",
"name ": "BodyFinal ",
"fields ": [{
"name ": "schema ",
"type ": "string "
},
{
"name ": "data ",
"type ": {
"type ": "array ",
"items ": {
"type ": "record ",
"name ": "DataFinal ",
"fields ": [{
"name ": "tna ",
"type ": [
"null ",
"string "
],
"default ": null
},
{
"name ": "aid ",
"type ": [
"null ",
"string "
]
}
]
}
}
}
]
}
}
]
}
How can i generate the case classes automatically using schema as:
case class JSONSchema(schema: String, body: BodyFinal)
case class BodyFinal(schema: String,data: List[DataFinal])
case class DataFinal(tna: Option[String], aid: Option[String])
And then can write a parser to validate the any json received using the case classes. So that if I change the schema in future and add/remove any fields in it then the case classes can be generated and validated against the JSON.
This question already has answers here:
Getting a single value from a JSON object using JSONPath
(4 answers)
Closed 3 years ago.
I have following JSON
{
"firstName": "John",
"lastName" : "doe",
"age" : 26,
"address" : {
"streetAddress": "naist street",
"city" : "Nara",
"postalCode" : "630-0192"
},
"phoneNumbers": [
{
"type" : "iPhone",
"number": "0123-4567-8888"
},
{
"type" : "home",
"number": "0123-4567-8910"
}
]
}
and $.phoneNumbers[:1].type json path to extract phone number type iPhone value but the output is
[
"iPhone"
]
I would like to get it as simple string like iPhone. How do i create the JSON path to strip double quote " and [ ?
You cannot remove [ & " directly from JSON Path, However, you can use this replace function given here https://community.apigee.com/questions/63281/how-to-remove-square-bracket-and-double-quotes-fro.html
var extracted_json = ["vIMS"]; // use context.getVariable("<<extracted-variable>>");
modifiedJson = JSON.stringify(extracted_json).replace(/[\[\]"]+/g,"");
context.setVariable("final-variable", modifiedJson)
By default, using JsonPath to process JSON means you will get the result as a JSONArray. So, you have to make one more step to get the desired result.
For example,
#Test
public void test() {
String json = "{\n" +
" \"firstName\": \"John\",\n" +
" \"lastName\" : \"doe\",\n" +
" \"age\" : 26,\n" +
" \"address\" : {\n" +
" \"streetAddress\": \"naist street\",\n" +
" \"city\" : \"Nara\",\n" +
" \"postalCode\" : \"630-0192\"\n" +
" },\n" +
" \"phoneNumbers\": [\n" +
" {\n" +
" \"type\" : \"iPhone\",\n" +
" \"number\": \"0123-4567-8888\"\n" +
" },\n" +
" {\n" +
" \"type\" : \"home\",\n" +
" \"number\": \"0123-4567-8910\"\n" +
" }\n" +
" ]\n" +
"}";
net.minidev.json.JSONArray iPhone = JsonPath.parse(json).read("$.phoneNumbers[?(#.type=='iPhone')].type");
System.out.println("Type : " + iPhone.get(0).toString());
}
, will eventually print Type : iPhone
My current json readable format in file is .
{"delete" : {
"_index" : "production",
"_type" : "listings",
"_id" : "f170321064",
"_version" : 6,
"result" : "deleted",
"_shards" : {
"total" : 1,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 175987,
"_primary_term" : 1,
"status" : 200
}
}
How to convert like below
{"delete" : {"_index" : "production-cire","_type" : "listings","_id" : "424-l-81694-f1703210641700147","_version" : 6,"result" : "deleted","_shards" : {"total" : 1,"successful" : 1,"failed" : 0},"_seq_no" : 175987,"_primary_term" : 1,"status" : 200}}
Not sure what language you are using but I think this will work for you.
let str = JSON.stringify({you_json})
if using java or android:
The string exactly as you wrote it, I'm not sure you can turn it into JSON. but if you change it a bit like what follows it gives what you want:
String str="{" +
"delete : { " +
"_index : production, " +
"_type : listings, " +
"_id : f170321064, " +
"_version : 6, " +
"result : deleted, " +
"_shards : { " +
"total : 1, " +
"successful : 1, " +
"failed : 0" +
"}, " +
"_seq_no : 175987, " +
"_primary_term : 1, " +
"status : 200" +
"}" +
"}";
JSONObject obj= null;
try {
obj = new JSONObject(str);
System.out.println(obj.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
see the output:
{"delete":{"_index":"production","_type":"listings","_id":"f170321064","_version":6,"result":"deleted","_shards":{"total":1,"successful":1,"failed":0},"_seq_no":175987,"_primary_term":1,"status":200}}
I am testing an AngularJS website locally. I'm having problems parsing JSON data using $http.get from a local JSON file.
When I define the JSON in my controller, I have no problems. However, when I get the JSON from a file (data.json), the JSON format is different, according to the JavaScript console.
How come the JSON formats are different? Specifically, the $http.get retrieved JSON has numeric keys. Can I simply remove the numeric keys? Or is there something wrong with my JSON declaration/syntax? Below is a slew of additional information.
Here is how I define it in my controller:
$scope.customerReviews = [
{
'id': '0',
'title': 'Outstanding Employee!',
'text': 'bar foo bar foo',
'image': '<img class="img-responsive img-hover" src="images/bob.jpg">',
'href': '',
'date': 'June 17, 2014',
'author': 'john',
'articleType': 'article',
'neverSettle': 'partnering',
'category': 'customerReviews'
},
{
'id': '1',
'title': 'hooray!',
'text': 'congratulations',
'image': '<img class="img-responsive img-hover" src="images/bob.png">',
'href': '',
'date': 'June 17, 2014',
'author': 'sir charles',
'articleType': 'article',
'neverSettle': 'innovating',
'category': 'customerReviews'
},
{
'id': '2',
'title': 'Outstanding Employee',
'text': 'bar foo foo',
'image': '<img class="img-responsive img-hover" src="images/bilbo.jpg">',
'href': '',
'date': 'June 17, 2014',
'author': 'johnny',
'articleType': 'article',
'neverSettle': 'engaging',
'category': 'customerReviews'
},
{
'id': '3',
'title': 'Thank you',
'text': 'much thanks',
'image': '<img class="img-responsive img-hover" src="images/x.jpg">',
'href': '',
'date': 'June 17, 2014',
'author': 'The Graduate College',
'articleType': 'article',
'neverSettle': 'innovating',
'category': 'customerReviews'
}
];
When I copy paste from [ to ]; into the Chrome developer tools console, I get the following output:
Like I said above, my current code prints my content perfectly. But if I try to get the JSON in an external file using $http.get, it doesn't print my content, and the JavaScript console shows a different JSON format.
Here is my $http.get code (in the controller):
// http get json content
$scope.customerReviews = [];
$http.get("js/models/data.json").success(function(data){
console.log("success!");
$scope.customerReviews = data;
console.log($scope.customerReviews);
return $scope.customerReviews;
});
Here is data.json. As you can see, this JSON file is different from how I define my controller. Specifically, the " and ' are switched to be JSON validation compliant. I ran this one through a JSON validator and it is formatted correctly. Also, when I copy paste this into the console, I get the first console output. Only when I do $http.get I get the "numeric keys" and my printing functions don't work.
[
{
"id ": "0 ",
"title ": "Outstanding Employee! ",
"text ": "too lazy to obfuscate all of my content",
"image ": "<img class='img-responsive img-hover' src='images/GladisTolsa.jpg'> ",
"href ": " ",
"date ": "June 17, 2014 ",
"author ": "Martha Castleberry ",
"articleType ": "article ",
"neverSettle ": "partnering ",
"category ": "customerReviews "
},
{
"id ": "1 ",
"title ": "Facilities Help ",
"text ": "too lazy to obfuscate all of my content",
"image ": "<img class='img-responsive img-hover' src='images/FernandoLopez.png'> ",
"href ": " ",
"date ": "June 17, 2014 ",
"author ": "Lucy Valenzuela ",
"articleType ": "article ",
"neverSettle ": "innovating ",
"category ": "customerReviews "
},
{
"id ": "2 ",
"title ": "Outstanding Employee ",
"text ": "too lazy to obfuscate all of my content",
"image ": "<img class='img-responsive img-hover' src='images/MariaAlvarado.jpg'> ",
"href ": " ",
"date ": "June 17, 2014 ",
"author ": "Martha Castleberry ",
"articleType ": "article ",
"neverSettle ": "engaging ",
"category ": "customerReviews "
},
{
"id ": "3 ",
"title ": "Thank you ",
"text ": "too lazy to obfuscate all of my content",
"image ": "<img class='img-responsive img-hover' src='images/MovingServices.jpg'> ",
"href ": " ",
"date ": "June 17, 2014 ",
"author ": "The Graduate College ",
"articleType ": "article ",
"neverSettle ": "innovating ",
"category ": "customerReviews "
}
]
So the $http.get request works. Here is the console output:
Phew. I apologize for the lengthiness of my question.
My Question: How come the seemingly equivalent JSONs are outputting different formats? Specifically, why does the $http.get retrieved JSON (the second one) have numeric keys? I need the second console output to have the same output as the first console output. Can I just remove the numeric keys? Or is there something wrong with my JSON declaration/syntax?
Any input is appreciated. Especially anything that could improve my AngularJS skills, and JSON knowledge. Thanks in advance.
EDIT: Thanks to everyone so far. Apparently those are array indexes written by Chrome developer tools, not numeric keys. I won't change my post title to avoid confusion for others. On request, here is how my printing works:
<!-- ng repeat of Blog Preview Rows (reversed) -->
<div ng-repeat="x in getCategory().slice().reverse() | limitTo:quantity " close="getCategory().splice(index, 1)">
<previews></previews>
<hr />
</div>
getCategory() is a function that gets the querystring of the URL using regex. As stated before, this works when the JSON is declared in the controller. Perhaps getCategory() is ran after $http.get, therefore not printing anything? Also note that I simply reverse the ng-repeat.
Here is the <preview> directive:
.directive('previews', function () {
return {
restrict: 'AEC',
replace: 'true',
templateUrl: 'js/views/articleCollection.htm'
};
});
articleCollection.htm:
<div class="row">
<div class="col-md-1 text-center">
<p><span ng-bind-html="x.articleType"></span></p>
<p><span ng-bind-html="x.neverSettle"></span></p>
<p><span ng-bind-html="x.date"></span></p>
</div>
<div class="col-md-5">
<a href="{{ x.href }}">
<span ng-bind-html="x.image"></span>
</a>
</div>
<div class="col-md-6">
<h3>
<span ng-bind-html="x.title"></span>
</h3>
<p>
by <span ng-bind-html="x.author"></span>
</p>
<p><span ng-bind-html="x.text"></span></p>
<a class="btn btn-default" href="{{ x.href }}">Read More <i class="fa fa-angle-right"></i></a>
</div>
</div>
Thanks again. Let me know how I can further clarify my question. Also let me know how I can improve anything AngularJS related. So far, the journey has been a doozy.
Q: How come the seemingly equivalent JSONs are outputting different formats?
A: Because they are valid either way. See more info of JSON's syntax here
Q:Specifically, why does the $http.get retrieved JSON (the second one) have numeric keys?
A: I am guessing you are talking about the array position index at each array of objects. They make array easier to recognize. Of course, for viewing purpose in console.
Q: I need the second console output to have the same output as the first console output. Can I just remove the numeric keys?
A: Same as above. Google chrome output the 'numeric keys' are just for developers like us to easily recognize the position of array of object. You don't need then in your .json file.
Q: Or is there something wrong with my JSON declaration/syntax?
A: Nope. According to examples your provided, you are doing just fine. Keep up the good work!
EDIT
I've done some research, and, ahhhhhh I see your problem now.
Apparently reading JSON locally cause problem, so you need to modify a little bit.
See this:
AngularJS: factory $http.get JSON file
EDIT 2
Let me give it another go.
I personally have trouble relying on $scope, especially that I would not recommend to return a $scope in a function.
Try this:
app.factory("factoryExample", ['$http', function ($http) {
return {
Main: $http.get("js/models/data.json")
}
}]);
//in controller
app.controller('MainController', ['$scope', 'factoryExample', function ($scope, factoryExample) {
factoryExample.Main.success(function(data){
$scope.customerReviews = data;
});
}]);
As your post mentioned it seems like you are able to get json locally properly, my bad. After this code, your $scope.customerReview should be working!
EDIT3
Give your JSON a name, for your example:
{ "foo":
[
{
"id ": "0 ",
"title ": "Outstanding Employee! ",
"text ": "too lazy to obfuscate all of my content",
"image ": "<img class='img-responsive img-hover' src='images/GladisTolsa.jpg'> ",
"href ": " ",
"date ": "June 17, 2014 ",
"author ": "Martha Castleberry ",
"articleType ": "article ",
"neverSettle ": "partnering ",
"category ": "customerReviews "
},
{
"id ": "1 ",
"title ": "Facilities Help ",
"text ": "too lazy to obfuscate all of my content",
"image ": "<img class='img-responsive img-hover' src='images/FernandoLopez.png'> ",
"href ": " ",
"date ": "June 17, 2014 ",
"author ": "Lucy Valenzuela ",
"articleType ": "article ",
"neverSettle ": "innovating ",
"category ": "customerReviews "
},
{
"id ": "2 ",
"title ": "Outstanding Employee ",
"text ": "too lazy to obfuscate all of my content",
"image ": "<img class='img-responsive img-hover' src='images/MariaAlvarado.jpg'> ",
"href ": " ",
"date ": "June 17, 2014 ",
"author ": "Martha Castleberry ",
"articleType ": "article ",
"neverSettle ": "engaging ",
"category ": "customerReviews "
},
{
"id ": "3 ",
"title ": "Thank you ",
"text ": "too lazy to obfuscate all of my content",
"image ": "<img class='img-responsive img-hover' src='images/MovingServices.jpg'> ",
"href ": " ",
"date ": "June 17, 2014 ",
"author ": "The Graduate College ",
"articleType ": "article ",
"neverSettle ": "innovating ",
"category ": "customerReviews "
}
]
}
Then use:
<div ng-repeat="items in customerReviews.foo">{{items.id}}</div>
and so on.
Finally got the website on a web server, and the same code threw sce unsafe errors.
I just had to trust it as HTML before returning!
HTML-trustifying helper function:
function arrayToHTML(data) {
for (i = 0; i < data.length; i++) {
data[i]["id"] = $sce.trustAsHtml(data[i]["id"]);
data[i]["title"] = $sce.trustAsHtml(data[i]["title"]);
data[i]["text"] = $sce.trustAsHtml(data[i]["text"]);
data[i]["image"] = $sce.trustAsHtml(data[i]["image"]);
data[i]["date"] = $sce.trustAsHtml(data[i]["date"]);
data[i]["author"] = $sce.trustAsHtml(data[i]["author"]);
data[i]["articleType"] = $sce.trustAsHtml(data[i]["articleType"]);
data[i]["neverSettle"] = $sce.trustAsHtml(data[i]["neverSettle"]);
data[i]["category"] = $sce.trustAsHtml(data[i]["category"]);
data[i]["href"] = $sce.trustAsHtml(data[i]["href"]);
}
}
Working Code:
// http get json content
$scope.customerReviews = [];
$http.get("js/models/data.json").success(function(data){
console.log("success!");
$scope.customerReviews = data;
console.log($scope.customerReviews);
arrayToHTML($scope.customerReviews); // This fixed it!
return $scope.customerReviews;
});