trouble parsing json string - javascript

I am trying to parse this simple json string:
var dataJSON = {};
var data;
dataJSON = {
"status": "OK",
"messages" : [{
"user" : {
"id" : "4",
"status" : "offline",
"name" : "dummy",
"pictures" : ["pic.jpg"]
},
"message" : "Hey",
"timestamp" : 1395660658
}, {
"user" : {
"id" : "2",
"status" : "online",
"name" : "dummy1",
"pictures" : ["pic1.jpg"]
},
"message" : "hello",
"timestamp" : 1395660658
}]
};
console.log('test');
console.log(dataJSON);
//parse data
data = JSON.parse(dataJSON);
but I am getting the following error:
"unable to parse json string"
I have mo idea why, cheers.

You don't have to parse it at all; it's a JavaScript object already.
The acronym "JSON" stands for JavaScript Object Notation. It's a restricted form of the native syntax in JavaScript for creating objects "on the fly". To say that another way, JavaScript's native object literal syntax is a superset of JSON. What you've typed in there, as the value of your "dataJSON" variable, is a JavaScript object literal expression. The value of such an expression is a reference to an object. No parsing necessary, since the JavaScript parser itself has already done so.
edit — if you really do need a JSON string for testing purposes, then I think the easiest way to do that is to use JSON.stringify() to convert an object into a string, and then pass it into the test code. In your example, that'd look like:
dataJSON = JSON.stringify({
"status": "OK",
"messages" : [{
"user" : {
"id" : "4",
"status" : "offline",
"name" : "dummy",
"pictures" : ["pic.jpg"]
},
"message" : "Hey",
"timestamp" : 1395660658
}, {
"user" : {
"id" : "2",
"status" : "online",
"name" : "dummy1",
"pictures" : ["pic1.jpg"]
},
"message" : "hello",
"timestamp" : 1395660658
}]
});
It's a little easier than trying to construct the string by hand because of the "quote quoting" nuisance. Of course the object you pass in should be one that actually can be represented as JSON, but your sample above is definitely OK.

Related

Not able to Parse JSON from Jenkins properly

I'm trying to parse JSON from Jenkins's API using request
request({method: 'GET', url}, function(error, response, body) {
console.log(body.toString());
var output_json = JSON.parse(body.toString());
console.log(output_json);
}
After I parse the JSON usingJSON.parse(), few values in the tags are lost.
Console output of text output before parsing JSON
{
"_class" : "My.FreeProject",
"actions" : [
{
},
{
"_class" : "FreeProject.Property",
"parameterDefinitions" : [
{
"_class" : "org.choice.Parameter",
"defaultParameterValue" : {
"_class" : "Property",
"value" : "master19.7.0"
},
"description" : "",
"name" : "BUILD_TAG",
"type" : "ChoiceParameter"
},
{
"_class" : "Parameter",
"defaultParameterValue" : {
"_class" : "Value",
"value" : ""
},
"description" : "Random Text",
"name" : "MY_TEST",
"type" : "StringParameterDefinition"
},
{
"_class" : "org.myclass",
"defaultParameterValue" : {
"_class" : "org.newclass"
},
"description" : "",
"name" : "TESTING",
"type" : "NodeParameterDefinition"
}
]
},
{
Console output of text output after parsing JSON
{ _class: 'My.FreeProject',
actions:
[ {},
{ _class: 'FreeProject.Property',
parameterDefinitions: [Object] },
{},
{},
{},
{},
{},
{},
{},
{},
{ _class: 'com.myclass' } ],
So after parsing JSON, I'm losing some of the text values. Is there a way I could retrieve all the information of the JSON from Jenkins? Thanks
It doesn't look like anything is missing. The value of parameterDefinitions is just collapsed. Either there is a toggle you can click on to expand it, or use console.dir instead.
Example from the Chrome console. Note how it shows [Array[1]] instead of [[[[]]]] after parsing the string into an object. However, the values is still four nested arrays.

updating mongodb using $push operator in angular-meteor

I am trying to push arrays from one collection to another.
this is the code I used in my server js
updateSettings: function(generalValue) {
let userId = Meteor.userId();
let settingsDetails = GeneralSettings.findOne({
"_id": generalValue
});
Meteor.users.update({
_id: userId
}, {
$push: {
"settings._id": generalValue,
"settings.name": settingsDetails.name,
"settings.description": settingsDetails.description,
"settings.tag": settingsDetails.tag,
"settings.type": settingsDetails.type,
"settings.status": settingsDetails.status
}
})
}
updateSettings is the meteor method. GeneralSettings is the first collection and user is the second collection. I want to push arrays from GeneralSettings to users collection. While I try this the result i got is like
"settings" : {
"_id" : [
"GdfaHPoT5FXW78aw5",
"GdfaHPoT5FXW78awi"
],
"name" : [
"URL",
"TEXT"
],
"description" : [
"https://docs.mongodb.org/manual/reference/method/db.collection.update/",
"this is a random text"
],
"tag" : [
"This is a demo of an Url selected",
"demo for random text"
],
"type" : [
"url",
"text"
],
"status" : [
false,
false
]
}
But the output I want is
"settings" : {
"_id" : "GdfaHPoT5FXW78aw5",
"name" : "URL",
"description" :
"https://docs.mongodb.org/manual/reference/method/db.collection.update/",
"tag" :"This is a demo of an Url selected",
"type" : "url",
"status" : false
},
What changes to be made in my server.js inorder to get this output
This is one case where you "do not want" to use "dot notation". The $push operator expects and Object or is basically going to add the "right side" to the array named in the "left side key":
// Make your life easy and just update this object
settingDetails._id = generalValue;
// Then you are just "pushing" the whole thing into the "settings" array
Meteor.users.update(
{ _id: userId },
{ "$push": { "settings": settingDetails } }
)
When you used "dot notation" on each item, then that is asking to create "arrays" for "each" of the individual "keys" provided. So it's just "one" array key, and the object to add as the argument.

Unable to print BSON object from javascript

My mongoDB collection looks like this :
{
"_id" : ObjectId("5070310e0f3350482b00011d"),
"emails" : [
{
"_id" : ObjectId("5070310e0f3350482b000120"),
"_type" : "Email",
"name" : "work",
"email" : "peter.loescher#siemens.com",
"current" : true
}
]
}
and this is the .js code i use to print the contents :
c = db.contacts.findOne( { "emails.email" : { $ne : null } }, { "emails" : 1 } )
print(c._id.toString() + " " + c.emails[0]);
when I try to run this javascript file, it is just displaying the id but not the email array.
output:
5070310e0f3350482b00011d [object bson_object]
but when I try c.emails[0].email is is giving proper result. i.e. peter.loescher#siemens.com
All I need is I want to display the whole emails embedded object.
i.e.
"emails" : [
{
"_id" : ObjectId("5070310e0f3350482b000120"),
"_type" : "Email",
"name" : "work",
"email" : "peter.loescher#siemens.com",
"current" : true
}
]
Where I am going wrong?. Any help would be appreciated.
You need printjson to output a nicely formatted JSON:
printjson(c.emails[0]);
Here it is the documentation.

writing more complex json schemas that have dependencies upon other keys

I've been writing simple JSON schemas but I ran into an API input call that is a bit more complex. I have one restful end route that can take 3 very different types of JSON:
localhost/foo
can take:
{ "type" : "ice_cream", "cone" : "waffle" ...}
or
{"type" : "hot_dog", "bun" : "wheat" ...}
If the "type" key contains "ice_cream", I only ever want to see the key "cone" and not the key "bun". Similiarly if "type" contains "hot_dog" I only want to see "bun" and not "cone". I know I can pattern match to make sure I only ever see type "ice_cream" or type "hot_dog", but I don't know how to force the requirement of certain other fields if that key is set to that value. I see that there is a json schema field called "dependency" but I haven't found any good examples on how to use it.
BTW, I'm not sure if this input JSON is good form (overloading the type of JSON structure it takes, effectively), but I don't have the option of changing the api.
I finally got some information about this - it turns out you can make a union of several different objects that are valid like so:
{
"description" : "Food",
"type" : [
{
"type" : "object",
"additionalProperties" : false,
"properties" : {
"type" : {
"type" : "string",
"required" : true,
"enum": [
"hot_dog"
]
},
"bun" : {
"type" : "string",
"required" : true
},
"ketchup" : {
"type" : "string",
"required" : true
}
}
},
{
"type" : "object",
"additionalProperties" : false,
"properties" : {
"type" : {
"type" : "string",
"required" : true,
"enum": [
"ice_cream"
]
},
"cone" : {
"type" : "string",
"required" : true
},
"chocolate_sauce" : {
"type" : "string",
"required" : true
}
}
}
]
}
I'm still not sure if this is valid JSON, since my Schemavalidator dies on some invalid input, but it accepts the valid input as expected.

Grabbing data from JSON using Javascript

Ok so I have a json output that looks like this:
{"Result" : [
{
"Id" : "5214",
"ParentReasonId" : "0",
"Description" : "Billing & Payment",
"SysName" : "Billing & Payment",
"SysCategory" : "Billing & Payment",
"ClientId" : "924",
"DispositionCount" : "6",
"IsActive" : true,
"ChildReasonCount" : "8",
"Attributes" : [],
"SortOrder" : "0",
"CreatedBy" : null
}
]
}
And I would like to pull the data for id and description out of this.
jQuery("#chained_child").cascade("#chained", {
ajax: { url: 'Customhandler.ashx?List=MyList' },
template: commonTemplate,
match: commonMatch
});
function commonTemplate(item) {
return "<option Value='" + item.Result.Id + "'>"
+ item.Result.Description + "</option>";
};
But for the life of me I can't get it to return the value I am looking for. I know this is something noobish but I am hitting a wall. Can anyone help?
If you examine your JSON string, your Result object is actually an array of size 1 containing an object, not just an object. You should remove the extra brackets or refer to your variable using:
item.Result[0].Id
In order to reference your variable using item.Result.Id you would need the following JSON string:
{
"Result" :
{
"Id" : "5214",
"ParentReasonId" : "0",
"Description" : "Billing & Payment",
"SysName" : "Billing & Payment",
"SysCategory" : "Billing & Payment",
"ClientId" : "924",
"DispositionCount" : "6",
"IsActive" : true,
"ChildReasonCount" : "8",
"Attributes" : [],
"SortOrder" : "0",
"CreatedBy" : null
}
}
One thing that has helped me immensely with JSON funkyness has been setting breakpoints in Firebug, which let's you step through the resulting object, and view its structure.
item.Result[0].Id works as Sebastian mentioned - however it only works if "item" is actually assigned a value. My guess is it's not.
In your commonTemplate function try doing console.log(item) and seeing what the result is.
As far as I see it on the plugin page, the argument send to the template callback is an
item from the JSON response, which is an Array. Your JSON response is an Object. I guess you're not sending the correct JSON response. But take that with a grain of salt, as I've never used this plugin.
Anyway, if I'm right, you're response should be:
[
{
"Result" :
{
"Id" : "5214",
"ParentReasonId" : "0",
"Description" : "Billing & Payment",
"SysName" : "Billing & Payment",
"SysCategory" : "Billing & Payment",
"ClientId" : "924",
"DispositionCount" : "6",
"IsActive" : true,
"ChildReasonCount" : "8",
"Attributes" : [],
"SortOrder" : "0",
"CreatedBy" : null
}
}
]
Ionut G. Stan's answer is correct. Your json output is not the correct format for the cascade plugin.
If you don't want to change your json, you can use the dataFilter option in the ajax settings to augment the data.
I've set up a working demo here: http://jsbin.com/ebohe (editable via http://jsbin.com/ebohe/edit )
Here's the pertinent javascript:
$(function(){
$('#chained_child').cascade(
'#chained',
{
ajax: {
url: 'Customhandler.ashx?List=MyList',
dataFilter: extractResult
},
template: customTemplate,
match: customMatch
}
);
function extractResult(data) {
return eval('(' + data + ')').Result;
}
function customTemplate(item) {
return $('<option />')
.val(item.Id)
.text(item.Description);
}
function customMatch(selectedValue) {
return this.ParentReasonId == selectedValue;
}
});
You might want to take a look at this JSON tutorial from IBM:
Mastering Ajax, Part 10: Using JSON for data transfer

Categories