Error in Reading Json String with backslash in JavaScript - javascript

I have Converted a C# class in Json Object after it I stringify that json Object then it converts with backslash(escaping character) and when i used following code to read the json string it gives me undefined message in alert .
<script>
var jsString = { "JsonString": ["{\"reachoutid\":1,\"user_ID\":1,\"question\":\"Best CMS in Microsoft .Net\",\"anonymous\":false,\"shared\":false,\"create_date\":\"\\/Date(-62135596800000)\\/\",\"update_date\":\"\\/Date(1327300086183)\\/\",\"status\":0,\"start_date\":\"\\/Date(-62135596800000)\\/\",\"end_Date\":\"\\/Date(-62135596800000)\\/\",\"reachoutfactorsList\":null,\"reachoutchoicesList\":[{\"reachoutid\":0,\"choice_ID\":4,\"orders\":0,\"description\":\"Sitecore\",\"preachOutID\":0,\"pchoice_ID\":4,\"porders\":0,\"pdescription\":\"Sitecore\"},{\"reachoutid\":0,\"choice_ID\":5,\"orders\":0,\"description\":\".Net Nuke \",\"preachOutID\":0,\"pchoice_ID\":5,\"porders\":0,\"pdescription\":\".Net Nuke \"},{\"reachoutid\":0,\"choice_ID\":6,\"orders\":0,\"description\":\"Drupal\",\"preachOutID\":0,\"pchoice_ID\":6,\"porders\":0,\"pdescription\":\"Drupal\"}],\"detail\":\"Write more text to check progress bar work properly.\",\"set_Listof_Tags\":null,\"tag\":null,\"get_Listof_Tags\":null,\"userstatus\":null,\"actType\":\"RO\"}"], "_getList_MyActivities": null, "_getList_MyPeersActivities": null, "userID": 1 }
for (i = 0; jsString.JsonString.length > i; i++)
{
alert(jsString.JsonString[i].reachoutid);
//"Giving Undefined Message "
}
</script>

Your JSON is stored as a string, not as a native object. To convert it back, change your alert( ... ) line to use JSON.parse( ... ) like this:
alert( JSON.parse(jsString.JsonString[i]).reachoutid )

Your JSON shouldn't be quoted. When it is, JS interprets is as a string instead of an object
var jsObject = { "JsonString": [{"reachoutid":1,"user_ID":1,"question":"Best CMS in Microsoft .Net","anonymous":false,"shared":false}]} // etc.

Related

JSON Parse not working, parsing two dimensional array

I am trying to parse this LOCAL XMLhttprequest, I am getting back the right response text and displaying it in safari.
When I make an object to JSON.parse() the responsetext,I am getting errors like "unidentified token '"' " or "expected '}' " no matter how I change the .txt file, it will not parse into an object for me
I have tried to change the .txt to the right JSON format with no luck
{playerGrid: [["3","2","2","2","2","2","2","3","3","3"], ["3","2","2","2","2","2","2","2","2","2"], ["3","2","2","2","2","2","2","2","2","3"],["3","2","2","2","2","2","2","2","2","3"], ["4","2","2","2","2","3","2","2","2","3"], ["2","2","2","2","7","3","2","2","2","3"], ["2","2","2","2","7","2","2","2","2","2"], ["2","2","2","3","3","3","2","2","2","2"], ["2","2","2,"2","2","2","2","2","2","2"], ["2","2","2","2","2","2","2","2","2","2"]],
computerGrid: [["2","2","2","7","4","9","9","2","2","2"], ["2","9","2","2","2","2","2","2","2","2"], ["2","9","2","2","2","2","2","2","2","2"], ["2","9","2","2","9","9","2","2,"2","2"], ["2","2","2","2","2","2","2","2","2","2"], ["9","9","9","9","9","2","2","2","2","2"], ["2","2","2","2","7","2","2","2","9","2"], ["2","2","2","2","2","2","2","2","9","2"], ["2","2","2","2","2","2","2","2","9","2"], ["2","2","2","2","2","2","2","2","9","2"]]};
here is my JOSN .txt
function fileRequest()
{
var localRequest = new XMLHttpRequest();
localRequest.open("GET", "sampleJSON.txt", false);
localRequest.send(null);
document.getElementById("jsonDiv").innerHTML = localRequest.responseText;
var jsonObject = JSON.parse(localRequest.response);
document.getElementById("jsonParsed").innerHTML = jsonObject.computerGrid;
}
here is my simple function, I first display the response, and then it errors when I am trying to parse the data.
Thanks
I expect an object that I can .computerGrid or .playerGrid.
You have some errors in your json, just search by "2,, there are 2 occurences, it should be "2",.
You are missing a closing ".
Also, in order to the JSON to be valid, it should look like this:
{"playerGrid":[["3","2","2","2","2","2","2","3","3","3"],["3","2","2","2","2","2","2","2","2","2"],["3","2","2","2","2","2","2","2","2","3"],["3","2","2","2","2","2","2","2","2","3"],["4","2","2","2","2","3","2","2","2","3"],["2","2","2","2","7","3","2","2","2","3"],["2","2","2","2","7","2","2","2","2","2"],["2","2","2","3","3","3","2","2","2","2"],["2","2","2","2","2","2","2","2","2","2"],["2","2","2","2","2","2","2","2","2","2"]],"computerGrid":[["2","2","2","7","4","9","9","2","2","2"],["2","9","2","2","2","2","2","2","2","2"],["2","9","2","2","2","2","2","2","2","2"],["2","9","2","2","9","9","2","2","2","2"],["2","2","2","2","2","2","2","2","2","2"],["9","9","9","9","9","2","2","2","2","2"],["2","2","2","2","7","2","2","2","9","2"],["2","2","2","2","2","2","2","2","9","2"],["2","2","2","2","2","2","2","2","9","2"],["2","2","2","2","2","2","2","2","9","2"]]}
Keys, playerGrid and computerGrid must be between ".
Use JSON.parse(localRequest.responseText)
Your JSON is incorrect, you are missing quotes around some numbers like "2,
Object Keys "playerGrid" and "computerGrid" must be quoted too
let d = `{
"playerGrid": [
["3","2","2","2","2","2","2","3","3","3"], ["3","2","2","2","2","2","2","2","2","2"],
["3","2","2","2","2","2","2","2","2","3"], ["3","2","2","2","2","2","2","2","2","3"],
["4","2","2","2","2","3","2","2","2","3"], ["2","2","2","2","7","3","2","2","2","3"],
["2","2","2","2","7","2","2","2","2","2"], ["2","2","2","3","3","3","2","2","2","2"],
["2","2","2","2","2","2","2","2","2","2"], ["2","2","2","2","2","2","2","2","2","2"]],
"computerGrid": [
["2","2","2","7","4","9","9","2","2","2"], ["2","9","2","2","2","2","2","2","2","2"],
["2","9","2","2","2","2","2","2","2","2"], ["2","9","2","2","9","9","2","2","2","2"],
["2","2","2","2","2","2","2","2","2","2"], ["9","9","9","9","9","2","2","2","2","2"],
["2","2","2","2","7","2","2","2","9","2"], ["2","2","2","2","2","2","2","2","9","2"],
["2","2","2","2","2","2","2","2","9","2"], ["2","2","2","2","2","2","2","2","9","2"]]
}`;
console.log(JSON.parse(d))
PS: you can always validate your json with codebeautify.org/jsonvalidator

Using JS to connect to an API and then output the JSON response

I'm trying to do a UK Postcode validation using JS by connecting to http://postcodes.io/ post code validation service.
When I post to api.postcodes.io/postcodes/POSTCODEVARIABLE/validate I should recieve a 200 response and result of either "True" or "False" depending on whether the postcode is valid or not.
However, when I try to receive the data (in JSON format) I get an error in the console:
"Uncaught SyntaxError: Unexpected token o in JSON at position 1"
Here is my code, if anyone could point out where I am going wrong, that would be great.
var cpostcode = 'RG1 8BT';
var cpostcode = cpostcode.replace(/\s+/g, '');
var myNewURL = 'https://api.postcodes.io/postcodes/' + cpostcode + '/validate';
var pcapi = new XMLHttpRequest();
pcapi.onreadystatechange = function() {
if (pcapi.readyState == XMLHttpRequest.DONE) {
alert(pcapi.responseText);
}
}
pcapi.open("GET", myNewURL, true);
pcapi.send(null);
var xyz = JSON.parse(pcapi);
console.log(xyz);
Like at #Youssef said you want to log the .responseText. You get that script error because pcapi is a XMLHttpRequest object and not valid json which JSON.parse() attempts to parse. If you want to learn more about what you can do with the pcapi object just console.log(pcapi) and you can see its {keys:values} or just read up on it.
JSON.parse() converts any JSON String passed into the function, to a JSON Object.
There is really no such thing as a "JSON Object". The JSON spec is a syntax for encoding data as a string. ... JSON is a subset of the object literal notation of JavaScript. In other words, valid JSON is also valid JavaScript object literal notation but not necessarily the other way around. - stackoverflow
var cpostcode = 'RG1 8BT';
var cpostcode = cpostcode.replace(/\s+/g, '');
var pcapi = new XMLHttpRequest();
var myNewURL = 'https://api.postcodes.io/postcodes/' + cpostcode + '/validate';
pcapi.open("GET", myNewURL, false);
pcapi.send();
var xyz = JSON.parse(pcapi.responseText);
console.log(xyz);

Using json objects in duktape

everybody. I've just integrated duktape in my c++ code so that I'm able to use javascript.
But the problem I can't solve right now : how to use json objects in javascript.
Assume I've got some javascript like
function hi(person) {
print ('hi, ' + person.name );
}
And json object :
{
'name' : 'duktape'
}
So now I need to call function hi with an argument of this json in my cpp code.
duk_eval_string(ctx, "function hi(person) {print ('hi, ' + person.name );}");
duk_push_global_object(ctx);
duk_get_prop_string(ctx, -1, "hi" ); // pushes function from loaded script to stack
auto json = "{'name' : 'duktape' }";
duk_push_string(ctx, json);
duk_pcall(ctx, 1);
The output I get tells, that object is not correct
hi, undefined
Would like to head any suggestions on who should be done to get it working! Thank's for your time :)
You need to use duk_json_decode:
char *json = "{\"name\": \"duktape\"}";
duk_push_string(ctx, json);
duk_json_decode(ctx, -1);
duk_pcall(ctx, 1);
duk_pop_2(ctx);
Output:
hi, duktape
Note that your original json is not valid, you need to use " as string delimiters instead of '.
Depending on what you really needs, you could also create the object manually:
duk_idx_t obj_idx = duk_push_object(ctx);
duk_push_string(ctx, "duktape");
duk_put_prop_string(ctx, obj_idx, "name");
duk_pcall(ctx, 1);
duk_pop(ctx);

Is there Any Way to Convert Mongo ObjectId into string by javascript/jquery

Is it possible to convert mongo objectId into string.
The above pictures shows data i received and shown in console.I need id value in string form .but ObjectId is returning as object
In Database id is look like this- 565d3bf4cefddf1748d1fc5e -objectId and i need id exactly like this –
According to the Mongo documentation:
a 4-byte value representing the seconds since the Unix epoch,
a 3-byte machine identifier,
a 2-byte process id, and
a 3-byte counter, starting with a random value.
You can check it out here: https://docs.mongodb.org/manual/reference/object-id/
So in javascript you could do something like this.
var mId = {
Timestamp:1448950573,
Machine:13565407,
Pid:1756,
Increment:8888962
};
function getId(mongoId) {
var result =
pad0(mongoId.Timestamp.toString(16), 8) +
pad0(mongoId.Machine.toString(16), 6) +
pad0(mongoId.Pid.toString(16), 4) +
pad0(mongoId.Increment.toString(16), 6);
return result;
}
function pad0(str, len) {
var zeros = "00000000000000000000000000";
if (str.length < len) {
return zeros.substr(0, len-str.length) + str;
}
return str;
}
console.log(getId(mId))
It produces "565d3b2dcefddf06dc87a282" which was not exactly the id you had, but that might just be a tweak or i was working with different data :D.
EDIT
Added a padding function so that zeros are not truncated.
Hope that helps
EDIT:
I assume you are using c# to connect to and serve documents from the mongo DB. In that case, there is a driver that also supports toString().
Here is an example using the mongo csharp driver:
using MongoDB.Bson;
using MongoDB.Bson.IO;
using MongoDB.Bson.Serialization;
using MongoDB.Driver;
// ...
string outputFileName; // initialize to the output file
IMongoCollection<BsonDocument> collection; // initialize to the collection to read from
using (var streamWriter = new StreamWriter(outputFileName))
{
await collection.Find(new BsonDocument())
.ForEachAsync(async (document) =>
{
using (var stringWriter = new StringWriter())
using (var jsonWriter = new JsonWriter(stringWriter))
{
var context = BsonSerializationContext.CreateRoot(jsonWriter);
collection.DocumentSerializer.Serialize(context, document);
var line = stringWriter.ToString();
await streamWriter.WriteLineAsync(line);
}
});
}
ORIGINAL:
These are Mongo ObjectId's and if you haven't already deserialised the document they should support a toString method that will return a hexadecimal string.
but if you want this applied to the whole document, using JSON.stringify(MogoDocument) should deserialize this for you into a plain object.

How to replace string values with numeric inside a json object used in google visualization api column chart

I have this Json string that i use for google chart visualization that needs to be in this exact format and i need to replace every value of "v" that is a number to its numeric value( the value without the ""). I should do some javascript replace function, but i couldn't find a way to move around the json object. Here is and example json string that i should modify :
{"cols":[
{"id":"r","label":"Reason","type":"string"},
{"id":"m","label":"Minutes","type":"number"}
],
"rows":[
{"c":[
{"v":"Flour - Blower","f":"Flour - Blower"},
{"v":"7","f":"7"}]},
{"c":[
{"v":"Whole Line - d","f":"Whole Line - d"},
{"v":"4","f":"4"}]},
{"c":[
{"v":"Flour - Pipework","f":"Flour - Pipework"},
{"v":"3","f":"3"}]},
{"c":[
{"v":"Horseshoe - Belt","f":"Horseshoe - Belt"},
{"v":"1","f":"1"}]}
],
"p":null
}
probably i should do something like :
var jsonStr = ...;
for (i in jsonStr.rows) {
for(j in jsonStr[i].c)
{
if (parseInt(jsonStr[i].c[j].v) != 'NaN') {
jsonStr.rows[i].c[j].v = parseInt(jsonStr.rows[i].c[j].v);
}
}
Since JSON is effectively a string, why not put the entire string through a global string.replace:
jsonStr = JSON.stringify(jsonStr);
jsonStr = jsonStr.replace(/"v":"(\d+)"/g, '"v":$1');
Jsfiddle demo
Well, the parsing seems okay to me. It's probably not working because you can't really check if a string contains a number or not by comparing something with NaN
This is because even NaN === NaN, famously, returns false.
I'd suggest that you use the isNaN method (which does use parseInt internally). So, something like this ought to work
for (i in jsonStr.rows) {
for(j in jsonStr[i].c)
{
if (!isNaN(jsonStr[i].c[j].v)) {
jsonStr.rows[i].c[j].v = parseInt(jsonStr.rows[i].c[j].v);
}
}
A function that returns string if isNaN else a number:
function convertNumberToInteger(val) {
if (isNaN(val)) {
return val;
} else {
return parseInt(val);
}
}
Usage:
convertNumberToInteger("sasdfasdf");
Output: "sasdfasdf"
convertNumberToInteger("3");
Output: 3
And if you really want to parse it you can do a forEach on the JSON object

Categories