how to display escape sequences in JSON in Java script text box - javascript

I am sending a JSON object from a servlet to JSP using AJAX. My JSON object contains a String value inside. and that string contains double quotes within that. My JSON does not parse it. I get the following error:
{"diagnosis":[{"NAME":"new_diagnosis_1 \[1020\]:2000000006001"},{"NAME":"new_diagnosis_2 \[1021\]:2000000006003"},{"NAME":"new_"dise"sed \[1023\]:2000000009001"},{"NAME":"new_d"ise"sef \[1024\]:2000000009003"}]}
note new_"dise"sed and new_d"ise"sef
I need a solution.

your json is not valid
try this
{
"diagnosis": [
{
"NAME": "new_diagnosis_1 [1020]:2000000006001"
},
{
"NAME": "new_diagnosis_2 [1021]:2000000006003"
},
{
"NAME": "new_\"dise\"sed [1023]:2000000009001"
},
{
"NAME": "new_d\"ise\"sef [1024]:2000000009003"
}
]
}
use \ to escape quotes
you can validate your json here
http://www.jsonlint.com/

Related

Need to parse JSON string with value is quoted curly braces

I need to parse JSON string.
I've tried JSON.stringify and then JSON.parse below sample string, but server performed escape sequencing
I used str.replace('/\\/g','') to remove the escape sequence but that doesnt help because if you look in the "default_request" key is wraps its value with "" which is doesnt allow me parse it using JSON.parse()
{
"request": {
"service_name": "authService",
"url": "https://some-url.com/{accounts}",
"default_request": "{\"authMethod\":\"somename\",\"multiCheck\":false}"
}
}
so I tried to replace "{ with { and }" with }
str.replace('/"{/g','{')).replace('/}"/g','}'))
but it creates another problem.
Favourable condition
{
"request": {
"service_name": "authService",
"url": "https://some-url.com/{accounts}",
"default_request": {\"authMethod\":\"somename\",\"multiCheck\":false}
}
}
default_request was stringifyied twice. to fix it, try this
jsonObject.request.default_request = JSON.parse(jsonObject.request.default_request);

Javascript export excel fill top column

I created a code that can export a file via excel the code is working fine without error but my problem is the excel file has a lot of spaces can.
as you can see in the image row 123 data is put in column 7 not in column
heres my code for exporting the data
export function download() {
var header = [];
var finalData = []
var group = [
{ "group_name": "123" },
{ "group_name": "123b" },
{ "group_name": "123ef" },
{ "group_name": "Accounts Payable" },
{ "group_name": "ADG JET TEAM" },
{ "group_name": "001 Approval" }
]
var member = [
{"001 Approval": "083817 - Ranjeet Kumar (ranjeet.kumar3#concentrix.com)" },
{ "001 Approval": "C01747 - Abid Shaikh (abid.shaikh1#concentrix.com)"},
{ "001 Approval": "C01747 - Abid Shaikh (abid.shaikh1#concentrix.com)"},
{ "123b": "C01747 - Abid Shaikh (abid.shaikh1#concentrix.com)"},
{
"123ef": "C01747 - Abid Shaikh (abid.shaikh1#concentrix.com)"
}
]
group.forEach(data=>{
header.push(data.group_name)
})
finalData.push(header)
header.forEach(headerData=>{
var temp = []
member.forEach(memberData=>{
if (headerData === Object.keys(memberData)[0]){
temp.push(memberData[Object.keys(memberData)[0]])
}else{
temp.push("")
}
})
finalData.push(temp)
})
exportToCsv('export.csv', finalData)}
the exportToexcel code is from here https://jsfiddle.net/jossef/m3rrLzk0/
Open your CSV in a text editor and and check the output, what are you using as separator and delimiter. This can be a CSV bad format (fields not surrounded by quotes, for ex), or a problem with excel configuration (csv delimiters and separators).
If you have data like that
field1, field2, field 3 supercool, this is a phrase, ops
It can be a problem, it should be something similar to
"field1", "field2", "field 3 supercool", "this is a phrase, ops"
In addition, try to open your csv with Google Sheets (docs), which will try to recognize the delimiters and separators automatically. See if it works.
A common problem for that is that your CSV is saparated by spaces or commas, but phrase can have a space and a comma which will be interpreted as a separator, and the whole document will break.
It can be useful to take a look at that link: Write a string containing commas and double quotes to CSV

Integrating PHP into JavaScript to fetch JSON

I installed PHP5 and Apache2 on an Linux vServer (8 Gb Ram ; 8 vCores) and I was scripting but I can't get rid of an error in my code. I'm trying to fetch JSON with integrated PHP but it doesn't work. Here is part of the source code:
function GameDetails(servername, serverurl, mapname, maxplayers, steamid, gamemode) {
var data = '<?php header("access-control-allow-origin: http://api.steampowered.com");$jsonData = file_get_contents('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=*REMOVEDREMOVEDREMOVED&steamids=76561197960435530');echo $jsonData;?>';
document.getElementById('server_name').innerHTML = jsonObj.response.players[0].personaname;
});
}
And here is the version after PHP Processing:
function GameDetails(servername, serverurl, mapname, maxplayers, steamid, gamemode) {
var data = '{
"response": {
"players": [
{
"steamid": "76561197960435530",
"communityvisibilitystate": 3,
"profilestate": 1,
"personaname": "Robin",
"lastlogoff": 1405647102,
"profileurl": "http://steamcommunity.com/id/robinwalker/",
"avatar": "http://media.steampowered.com/steamcommunity/public/images/avatars/f1/f1dd60a188883caf82d0cbfccfe6aba0af1732d4.jpg",
"avatarmedium": "http://media.steampowered.com/steamcommunity/public/images/avatars/f1/f1dd60a188883caf82d0cbfccfe6aba0af1732d4_medium.jpg",
"avatarfull": "http://media.steampowered.com/steamcommunity/public/images/avatars/f1/f1dd60a188883caf82d0cbfccfe6aba0af1732d4_full.jpg",
"personastate": 0,
"realname": "Robin Walker",
"primaryclanid": "103582791429521412",
"timecreated": 1063407589,
"personastateflags": 0,
"loccountrycode": "US",
"locstatecode": "WA",
"loccityid": 3961
}]
}
}';
alert data;
document.getElementById('server_name').innerHTML = data.response.players[0].personaname;
});
}
I know its a loading screen for a Garrys Mod Server. The Debug Console from Firefox says:
SyntaxError: unterminated string literal.
But it's just normal JSON. JSON examples from web works without errors.
var data = '{
There's your unterminated string literal.
You can't have a literal new line in the middle of a string literal in JS.
Later, you are trying to access data as an object, not a string, anyway. Get rid of the quotes around it.

Accessing JSON data with colon in the label

I have json data with a colon in the label (see responsedata) which I'm finding difficult to access in Angular with the following code:
<li ng-repeat="i in items.autnresponse.responsedata | searchFor:searchString"> <p>{{i.autn:numhits}}</p> </li>
I keep getting an error like this:
Error: [$parse:syntax] Syntax Error: Token ':' is an unexpected token at column 7 of the expression [i.autn:numhits] starting at [:numhits].
JSON data excerpt:
"autnresponse": {
"action": {
"$": "QUERY"
},
"response": {
"$": "SUCCESS"
},
"responsedata": {
"autn:numhits": {
"$": "92"
},
"autn:totalhits": {
"$": "92"
},
"autn:totaldbdocs": {
"$": "188"
},
"autn:totaldbsecs": {
"$": "188"
},
Does anybody know a way around this?
I'll assume I know the answer to my question from the comments and post what would be my response:
Assumption
Your JSON parses fine but your code can't access something in the resulting data structure
Answer
Use square bracket notation with a string:
var x = i['autn:numhits'];
The same can be used when you have a property name in a variable. Using your same example:
var propertyName = 'autn:numhits';
var x = i[propertyName];
Addendum
For Angular template, try
{{i['autn:numhits']}}
Use brackets to access it like a dictionary rather than dot notation. Replace {{i.autn:numhits}} with {{i['autn:numhits']}}
As a heads up, if you want to wrap autn:numhits with double quotes you will need to html escape them.

Jquery Autocomplete with json fails

I am using the auto complete plugin by Devbridge and I have it all installed here is my code:
$(document).ready(function(){
$('#request_task').autocomplete({
serviceUrl: '<%= ajax_path %>',
minChars:1,
width: 300,
delimiter: /(,|;)\s*/,
deferRequestBy: 0, //miliseconds
params: { artists: 'Yes' },
});
});
This request hits my rails action and returns this json. there is only one object returned but most of the time there will be more then 1...this was just a test case:
[
{
"user": {
"salt": "somthing",
"name": "john",
"encrypted_password": "92dadsfa6b001ffe71c3c1d8e9fb76c42d1c8afeffa739de9063d94206c",
"created_at": "2010-09-10T14:10:54Z",
"updated_at": "2010-09-10T14:10:54Z",
"admin": null,
"id": 1,
"remember_token": "c945522b3eb0a25e36bb39155fc05b3eec301ac5e2196956f2e6f86b4b22c987",
"email": "test#gmail.com"
}
}
]
I can clearly see the request in firebug but I am not getting anything for the autocomplete and it errors out...Am i missing anything...My error is
a.suggestions is undefined
I think you need to read a little further down the developers page as your response is in the wrong format:
Web page that provides data for Ajax
Autocomplete, in our case
autocomplete.ashx will receive GET
request with querystring ?query=Li,
and it must return JSON data in the
following format:
{
query:'Li',
suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'],
data:['LR','LY','LI','LT']
}
Notes:
query - original query value
suggestions - comma separated array of suggested values data
(optional) - data array, that contains values for callback function when data is selected.
Sincere advice , dont construct JSON Strings. Please go for an API.
If you are using java, check this out http://www.json.org/java/
and make sure to set content-type in response as application/json
YOUR JSON is in a wrong format
Check their correct format
{
query:'Li',
suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'],
data:['LR','LY','LI','LT']
}

Categories

Resources