This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JSON pretty print using JavaScript
I'm working on a project that will be used to help analyse and understand JSON arrays by future developers of a platform. I'm referencing Facebook's brilliant Graph Explorer page, seen here, and want to output our array in a prettified, correctly tab indented and line breaker array, just as it does on the explorer.
The arrays are outputted to a textarea, and because of this I think I'm running into issues with the line breaking and tabbing. I've also tried using the prettify library, but with no luck.
Example:
{"outcome" : "success", "result" : {"name" : "messaging-sockets", "default-interface" : "external", "include" : [], "socket-binding" : {"messaging" : {"name" : "messaging", "interface" : null, "port" : 5445, "fixed-port" : null, "multicast-address" : null, "multicast-port" : null}, "messaging-throughput" : {"name" : "messaging-throughput", "interface" : null, "port" : 5455, "fixed-port" : null, "multicast-address" : null, "multicast-port" : null}}}, "compensating-operation" : null}
To:
{
"outcome":"success",
"result":{
"name":"messaging-sockets",
"default-interface":"external",
"include":[
],
"socket-binding":{
"messaging":{
"name":"messaging",
"interface":null,
"port":5445,
"fixed-port":null,
"multicast-address":null,
"multicast-port":null
},
"messaging-throughput":{
"name":"messaging-throughput",
"interface":null,
"port":5455,
"fixed-port":null,
"multicast-address":null,
"multicast-port":null
}
}
},
"compensating-operation":null
}
You may use JSON.stringify:
JSON.stringify(jsonobj,null,'\t')
See the demo.
UPDATE: If you don't have jsonobj,but have json string,then before using stringify function,convert json string to json object by this line:
jsonobj = JSON.parse(jsonstring);
Related
So I have a collection called "contributors." Within that collection the objects look like this:
{
"_id" : ObjectId("5ef1f75f7e6fb579ed3e5e8a"),
"#attributes" : {
"cand_name" : "name",
"cid" : "",
"cycle" : "",
"origin" : "",
"source" : "",
"notice" : ""
},
"contributor" : [
{
"#attributes" : {
"org_name" : "National Beer Wholesalers Assn",
"total" : "20000",
"pacs" : "20000",
"indivs" : "0"
}
},
{
"#attributes" : {
"org_name" : "Alabama Power",
"total" : "15000",
"pacs" : "10000",
"indivs" : "5000"
}
},
... with 10 "#attributes" objects in the "contributor" array.
What I need to do is query this whole collection to find each cand_name object that includes a certain org_name, which I'm already uncertain of how to do (since every time I've tried to query with a string it replaces the spaces in my string with %20).
But then I need to display a table with all the cand_name objects that included that org_name with the total, pacs, and indivs numbers that correspond to that cand_name & org_name.
To be super clear here I'm trying to make a table that displays every politician that a company has given money to (and how much).
So through all this I'm looking in multiple levels of each object and need to display data from all those levels together in one table. I may just be overthinking this, but it seems like it's going to be a complicated query...
Help?
Figured this out! Ended up working with the backend guy on our project and he did it all on backend.
This is the javascript Object (just a small part of it):
dataToReturn = {
"dimensionsDisplayType" : [
"dropdown","swatch",
],
"pwEnabledDimensionMap" : {
"size_name": true,
"color_name": true
},
"isPWBadgeEnabled" : true,
"isImmersiveExperience" : false,
"isTabletWeb" : false
}
So in PHP it will look like:
<?php
$jsObjStr = '{
"dimensionsDisplayType" : [
"dropdown","swatch",
],
"pwEnabledDimensionMap" : {
"size_name": true,
"color_name": true
},
"isPWBadgeEnabled" : true,
"isImmersiveExperience" : false,
"isTabletWeb" : false
}';
But if we would like to parse it with json parse we cant In PHP since its not a clean JSON format because of
"dimensionsDisplayType" : [
"dropdown","swatch",
]
The keys containing object like "dimensionsDisplayType" can be unpredictable so cleaning with regex for example wont help much.
The one that works is
JSON.stringify(dataToReturn)
But in my case I can not run client side code sot it must be converted into the correct JSON format in server side with PHP. I was searching a lot online but I got not any satisfying function or library.
How can this be solved ?
You could try cleaning the string with this regex, this will look for a comma followed by optional whitespace and a close ] and replace this with the content minus the comma...
$jsObjStr = preg_replace("/,(\s*?])/", "$1", $jsObjStr);
This question already has answers here:
How to query nested objects?
(3 answers)
Closed 6 years ago.
Here's my document:
"_id" : "dAWcFHJzDPJ2XT9Sh",
"createdAt" : ISODate("2016-04-22T18:03:47.761Z"),
"services" : {
"password" : {
"bcrypt" : "$2a$10$NYf53o/Uu8PvHPsGllRGA.WLbVpspNM4jk/6FtCzZLW.70.uQ2HXe"
},
"resume" : {
"loginTokens" : [
{
"when" : ISODate("2016-04-22T18:03:47.771Z"),
"hashedToken" : "dECxxuV/QyU2AU+/Zcrqc2Ftq64ZTrdHj5mN/rTGrxU="
}
]
}
},
"emails" : [
{
"address" : "Adammoisa#gmail.com",
"verified" : false
}
],
"profile" : {
"first_name" : "Adam",
"last_name" : "Moisa"
}
I want to search for an email in emails[i]address
Here's what I've tried (I'm using Meteor; Meteor.users.find({}).fetch() returns all users in database as objects formatted like above):
Meteor.users.find({"emails[0]address": "Adam"}).fetch();
I want that to return the above object as "Adam" is an email in emails[0]address
Thanks!
No need to specify the index.
Meteor.users.find({"emails.address": "Adam"}).fetch();
The index doesn't need to be specified, so you can do this:
Meteor.users.find({"emails.address": "Adam"}).fetch();
However if you do want to use a specific index, do this:
Meteor.users.find({"emails[0].address": "Adam"}).fetch();
Figured it out:
Meteor.users.find({"emails.address": "Adammoisa#gmail.com"}).fetch();
You can just do emails.address and it will match any address key with your value from any array in emails.
(Used regex from searchSource to make it work with anything that matches:
function buildRegExp(searchText) {
// this is a dumb implementation
var parts = searchText.trim().split(/[ \-\:]+/);
return new RegExp("(" + parts.join('|') + ")", "ig");
}
I need to pull the value of property "title"
KV = {
clientPath: '/0000000000/client',
serverPath: '',
application: '/00000000/client/application/player.js',
properties: '/000000000/client/custom-config/AppProperties.js',
pollingEnabled: false,
customerConfig: {},
presentationTypeConfig: {},
kuluConfig: {},
kulu: {
"guid" : "XXXXXXX",
"title" : "XXXXX",
"createdInApp" : false,
"allowFeedback" : true,
"publisher" : {
"id" : 000000001,
"username" : "XXXXXXX",
"name" : "XXXXXXXX"
},
I tried looping but I just get returned undefined.
I have no access to the code to change it.
Have you tried this?
KV.kulu.title
first of all: the json you have posted is invalid. publisher-property has only an opening curly bracket.
second: here's a working fiddle, with valid json and just the code kv.kulu.title which does exactly what you are (literally) asking for:
http://jsfiddle.net/k75cxdkh/1/
edit: I'm just guessing here, but re-reading your question and json code, it seems you try to loop over an array of objects to get a nested object by it's value dynamically. When trying this, do it e.g. like this (using underscorejs):
var arr = _.filter(KV, function(obj) {
return _.some(obj.kulu, {id: ID_TO_FIND});
});
if not, nevermind. It's just a bit weird you are asking for a such common task.
quick and easy: KV.kulu.title no loop required!
I have the following documents in my mongodb collection:
{
"current" :
{
"aksd" : "5555",
"BullevardBoh" : "123"
},
"history" :
{ "1" : {
"deleted" : false,
"added" : false,
"date" : "21-08-2014"
}
},
{ "2" : {
"deleted" : false,
"added" : false,
"date" : "01-01-2013"
}
},
"_id" : ObjectId("53f74dad2cbfdc136a07bf16"),
"__v" : 0
}
I have multiple of these documents. Now I want to achieve two things with my Mongoose/Express API.
Query for all nested "current" in each document and retrieve them as JSON objects like such: {"aksd":"5555","BullevardBoh":"123"},{..},{..}.
Retrieve all history revisions (1,2...) where "date" is smaller than a given date.
As you can clearly see this is a kind of versioning I am trying to implement. I would also be interested if this kind of data structure will get indexed by MongoDB and if there is possibly a better way. (e.g. with arrays inside objects?)
This isn't working in MongoDB:
db.ips.findOne({current.aksd: {$exists:true}});
I think the quotes around the field are missing here:
db.ips.findOne({current.aksd: {$exists:true}});
This should work instead:
db.ips.findOne({"current.aksd": {$exists:true}});
While Ritesh's reply was a step in the right direction, I rather wanted to fetch the current object literal and its members inside the document not the whole document.
1.) Query for all nested "current" in each document
db.ips.find({"current":{$exists:true}}, {"current":1});
This is giving back all nested documents where the aksd literal is present:
{ "current" : { "aksd" : "5555", "BullevardBoh" : "123" }, "_id" : ObjectId("53f74dad2cb3dc136a07bf16") }
...
2.) Retrieving history revisions where date is smaller then a given date:
db.ips.find({"history.date": {$lt: "01-01-2014"}},{history:{$elemMatch:{date: {$lt:"01-01-2014"}}}});
Giving back the wanted nested date literal(s):
{ "historie" : [ { "date" : "01-01-2013", "added" : false, "deleted" : false } ], "_id" : ObjectId("53faf20f399a954b2b7736b6") }