Using JSON.parse for accessing a json file - json

jQuery Code:
$(document).ready(function(){
$.getJSON('dat.js', function(data) {
var obj = JSON.parse(data);
alert(obj[0].title);
});
});
My JSON file :
{
"posts":
[
{
"title": "ajax | Programming ",
"url": "hello"
},
{
"title": "jQuery and Ajax Demos Pard - 3",
"url": "how are you"
},
]
}
Its giving me an error JSON.parse:unexpected character. But when I tried to do it by taking the json inside an array its ok then. I want to access the data from json file itself

you do parseJSON when your input is a json string and u expect an object. Here, getJSON is already giving u the response as an object.
try this
$(document).ready(function(){
$.getJSON('dat.js', function(obj) {
alert(obj.posts[0].title);
});
});

A Quick jslint check says that you have invalid json at line 11 },, Try removing the comma from the last member of "posts" and see if that help
{
"title": "jQuery and Ajax Demos Pard - 3",
"url": "how are you"
}, <---- THIS

Related

Go dialogflow sdk WebhookResponse doesn't return the correct json

I'm trying to write a webhook in Go for Dialogflow, I'm using the apiv2 of the official SDK
google.golang.org/genproto/googleapis/cloud/dialogflow/v2
But I can't generate a correct response using the official sdk.
What I mean is that following the documentation and the WebhookResponse struct I can't generate the expected json for the response.
This is the piece of code that I'm using:
response = dialogflow.WebhookResponse{
FulfillmentMessages: []*dialogflow.Intent_Message{
{
Message: &dialogflow.Intent_Message_Card_{
Card: &dialogflow.Intent_Message_Card{
Title: "Title",
Subtitle: "Subtitle",
ImageUri: "https://example.com/images/example.png",
Buttons: []*dialogflow.Intent_Message_Card_Button{
{
Text: "Button",
Postback: "https://example.com/path/for/end-user/to/follow",
},
},
},
},
},
},
}
This is the json that it generates:
{
"fulfillment_messages": [
{
"Message": {
"Card": {
"title": "Title",
"subtitle": "Subtitle",
"image_uri": "https://example.com/images/example.png",
"buttons": [
{
"text": "Button",
"postback": "https://example.com/path/for/end-user/to/follow"
}
]
}
}
}
]
}
But this is the json that I should send back (according to the official documentation)
"fulfillmentMessages": [
{
"card": {
"title": "card title",
"subtitle": "card text",
"imageUri": "https://example.com/images/example.png",
"buttons": [
{
"text": "button text",
"postback": "https://example.com/path/for/end-user/to/follow"
}
]
}
}
]
}
So my json doesn't work, because it has the Message that shouldn't be there, and Card with uppercase first letter. I've tried to send the json of the documentation and it works, Dialog Flow responds correctly.
I don't understand how to generate the correct json using the official SDK. Please consider that I'm pretty new using Go Lang. This is my first project.
This is the documentation that I'm using at the moment:
https://pkg.go.dev/google.golang.org/genproto/googleapis/cloud/dialogflow/v2?tab=doc#WebhookResponse
As you can see the FulfillmentMessages is an array of Intent_Message
FulfillmentMessages []*Intent_Message
And the Intent_Message has to contain Message (here the documentation)
Thanks in advance for any help and suggestions.
H2K
UPDATE:
if I use log.Println(response) I can see the correct response inside the log
fulfillment_messages:{card:{title:"Title" subtitle:"Subtitle" image_uri:"https://example.com/images/example.png" buttons:{text:"Button" postback:"https://example.com/path/for/end-user/to/follow"}}}
It is not a JSON but the structure is correct, no Message, no Card...
So the problem is when I return it with Gin and the command:
c.JSON(200, response)
I've found a solution!
I need to use the jsonpb marshaler and return it as string with Gin
Here an example:
m := jsonpb.Marshaler{}
result, _ := m.MarshalToString(response)
c.String(200, result)
I've totally went crazy on it, I hope that it could be helpful for someone else.

Removing back Slash from JSON in angularjs

I am getting a JSON object from a webservice which after JSON.stringify().I am getting this output-`
[
{
"user": "A220",
"shorttext": "shanghai",
"reportedBy": "S,A",
"questions": "[{\"question\":\"Q1\",\"is_mand\":\"0\",\"type\":\"text\",\"answer\":\"w\",\"ansYesOrNo\":false,\"ansDetails\":\"\"},{\"question\":\"Q2\",\"is_mand\":\"0\",\"type\":\"text\",\"answer\":\"ed\",\"ansYesOrNo\":false,\"ansDetails\":\"\"}]",
"notifno": "20143995",
"error": "",
"createdOn": "2015-09-09 13:08:36",
"Id": 0,
"$$hashKey": "object:89"
}
]
`
I want to remove all these back slash.
I tried using
var a=JSON.stringify(<that object>).replace(/\\/g, "");
But its giving result as a form string that too INVALID like this-
[
{
"user": "A220",
"shorttext": "shanghai",
"reportedBy": "S,A",
"questions": "[{"question":"Q1","is_mand":"0","type":"text","answer":"w","ansYesOrNo":false,"ansDetails":""},{"question":"Q2","is_mand":"0","type":"text","answer":"ed","ansYesOrNo":false,"ansDetails":""}]",
"notifno": "20143995",
"error": "",
"createdOn": "2015-09-09 13:08:36",
"Id": 0,
"$$hashKey": "object:89"
}
]
My only objective is to remove the back slash without changing the data type.
I want to access the first question of questions.
Its not working...
JsFiddle link-LINK
You dont need to do JSON.stringify() in web service response. You can directly work like
$http.get('/someUrl').
then(function(response)
{
$scope.data = response;
},
function(response)
{
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Now you have print in html like {{data}}
You can use this method to remove backslash from a JSON string
var data = {"\\id\\":"\\23232\\","\\pass\\":"\\1434\\"};
console.log(data);
var b=JSON.stringify(data);
str = b.replace(/\\/g, '');
console.log(str);

React get JavaScript Object from JSON file?

The issue is that I'm trying to get a JavaScript object like the following:
[
"id" : 11,
"name" : "Peter"
"other": {
"id": 22,
"item": 534
},
"main": false
]
Since I want to get this via reactjs: I trying to do this:
http.get(API.BASE_URL + API.USER_INFO)
.accept('Application/json')
.end((err, res) => {
//console.log(x);
console.log(err);
console.log(res);
});
When I try a normal json string I get the right result, but with this javascript object I get:
Error: Parser is unable to parse the response
undefined
Has anyone come across this before? Any idea?
What you're trying to parse isn't valid JSON (as well as JavaScript) because you've written it out as an array, but still use key/value pairs as if it were an object. Try this instead:
{
"id": 11,
"name": "Peter",
"other": {
"id": 22,
"item": 534
},
"main": false
}

Removing excess comma on JSON Object

Currently been working on eliminating the excess "," comma on the json object I have below.
{"rules": {
"1000": {
"action": "2",
"category": "skype",
"entity": "Private",
"id": "1000",
},
"1200": {
"action": "2",
"category": "http",
"entity": "Public",
"id": "1200",
},
"100": {
"action": "2",
"category": "ftp",
"entity": "Public",
"id": "100",
},
"0": {
"entity": "Private",
"category": "alcohol, tobacco",
"action": "1",
"id": "low",
},
"3000": {
} }}
Maybe you have some insights on what's the cleanest way to eliminate it using AngularJS.
The data was parsed from this code snippet.
var request = {
url: 'sample/uri',
method: "GET",
transformResponse: specialTransform
};
var response = $q.defer( );
$http( request ).success( function( THIS DATA -> data, status ) {
eval
var fixTrailingCommas = function (jsonString) {
var jsonObj;
eval('jsonObj = ' + jsonString);
return JSON.stringify(jsonObj);
};
fixTrailingCommas('{"rules": { "1000": { "action": "2", "category": "skype", "entity": "Private", "id": "1000" , } } }');
Please use eval here only if you completely trust incoming json, and also be aware of other eval evils as described on MDN and its note on JSON parsing
Note that since JSON syntax is limited compared to JavaScript syntax, many valid JavaScript literals will not parse as JSON. For example, trailing commas are not allowed in JSON, and property names (keys) in object literals must be enclosed in quotes. Be sure to use a JSON serializer to generate strings that will be later parsed as JSON.
You may also choose to rely on implementation of JSON2 by Douglas Crockford which uses eval internally
On current browsers, this file does nothing,
preferring the built-in JSON object. There is no reason to use this file unless
fate compels you to support IE8, which is something that no one should ever
have to do again.
But because we really need to use this library, we have to make few code modifications, e.g. simply comment out JSON type check, which will then override native browser object (or we may also introduce new JSON2 global variable)
//if (typeof JSON !== 'object') {
JSON = {};
//}
P.S. Other parsing fuctions json_parse.js and json_parse_state.js, which don't use eval, throw a syntax error
Angular part
var config = {
transformResponse: function (data, headers) {
if(headers("content-type") === "application/json" && angular.isString(data)) {
try {
data = JSON.parse(data);
} catch (e) {
// if parsing error, try another parser
// or just fix commas, if you know for sure that the problem is in commas
data = JSON2.parse(data);
}
return data;
} else {
return data;
}
}
};
$http.get("rules.json", config).success(function (data) {
$scope.rules = data;
});
So as you said, the JSON is wrongly generated on the server you are taking it from, can you change the way it is generated there? (Follow this: Can you use a trailing comma in a JSON object?)
In case you are unable to do so, you need to use something like mentioned here:
Can json.loads ignore trailing commas?
library to repair a JSON object, like: https://www.npmjs.com/package/jsonrepair
(try some online fix tool here: http://www.javascriptformat.com/)
or some regexp magic

JSON Parsing Error

I got problem. I have this JSON automatically generated by Open Flash Chart php library. The problem is, OFC report JSON Parse Error [Syntax Error] while test result using http://www.jsonlint.com/ report that my JSON is fine. But, w3c parser report error too:(
Any help?
Here's the JSON:
{
"title": "Followers Trend",
"elements": [
{
"type": "area_hollow",
"fill-alpha": 0.35,
"values": [
],
"colour": "#5B56B6",
"text": "Followers",
"font-size": 12
}
],
"x_axis": {
"colour": "#A2ACBA",
"grid-colour": "#D7E4A3",
"offset": false,
"steps": 4,
"labels": {
"steps": 2,
"rotate": "vertical",
"colour": "#A2ACBA",
"labels": [
]
}
},
"x_legend": {
"text": "Week Trend (2009-08-17 - 2009-08-24)",
"style": "{font-size: 20px; color: #778877}"
},
"y_axis": {
"min": 0,
"max": 150,
"steps": 30
}
}
A few things I learned while playing with JSON is:
If you have validate the JSON on various JSON validation services and the result is GOOD. But, when you failed to eval it, try to wrap your JSON using ( and ) => ({jsondata})
var json = eval( "(" + jsonString + ")" );
NEVER build the JSON yourself. It's a gate to failure. Always use official or popular JSON library (depending on your language). For example:
On PHP: use json_encode()
On Java Android: use org.json.JSONObject
A list of all other available library to play with JSON is listed in JSON official page.
To display and format JSON data, you can use JSONViewer.
I think the w3c parser is having issues, I couldn't even get it to parse this:
{
"title" : "Followers Trend"
}
It gave me this error:
Validation errors:
lexer couldn't parse at "{
"title" : "Followers Trend"
}"
http://json.bloople.net helps you visualise the code to find and correct errors.
try this code, JSON.parse() method is not able to handle string which is in a
single quote as a value in the right-hand side. also if you want to handle the
UTF-8 character code, then it will do.
parseJSON = function() {
var data = {};
var reader = new FileReader();
reader.onload = function() {
try {
data = JSON.parse(reader.result.replace(/'/g, "\""));
console.log(data)
} catch (ex) {
console.log('error' + ex);
}
};
reader.readAsText(fileSelector_test[0].files[0], 'utf-8');
}