How can I pull nested JSON values from python using dictionaries? - javascript

My database is formatted like this:
{
"latitude" : 41.884629,
"longitude" : -87.648764,
"name" : "Bar Siena",
"placeID" : "ChIJf3h_t9osDogReehZO7Hgk50",
"vibes" : {
"LGpswrvLgfYppcBG4bpmNzXQVoU2" : {
"rating" : 1,
"timestamp" : 1.477961061358844E9
},
"OSzA2KhTBWS3pxVnCZ6eScAuNDG3" : {
"rating" : 5,
"timestamp" : 1.477955566836665E9
}
}
}
I want to pull both the names of each bar, and every rating corresponding to it in the vibes table. My code looks like this:
firebase = pyrebase.initialize_app(config)
db = firebase.database()
for i in range(1,100):
venues = db.child("venues").child(i).get()
dict = (venues.val())
print(dict['name'])
So far i'm only able to get the names, but i'm not sure how to go deeper and get the ratings. My database is managed using Firebase, and I'm using a python library called Pyrebase that's just a wrapper for the javascript api. I'm having trouble because each vibe has a generated hash key so i'm not sure how to go deeper. Any thoughts?

vibes probably comes as a dictionary. What you want are the ratings of each hash key, so you can do something like
for hashkey, vibe_dict in dict['vibes'].items(): # dict is a Python keyword, so it's a bad choice for a variable!
print(hashkey, vibe_dict['rating'])

I am not sure about firebase, but in plain python you may do it like:
>>> for vibe in my_json['vibes'].values():
... print vibe['rating']
...
1 # Rating of item 1
5 # Rating of item 2
where my_json is the dict build from your json:
{
"latitude":41.884629,
"longitude":-87.648764,
"name":"Bar Siena",
"placeID":"ChIJf3h_t9osDogReehZO7Hgk50",
"vibes":{
"LGpswrvLgfYppcBG4bpmNzXQVoU2":{
"rating":1,
"timestamp":1.477961061358844E9
},
"OSzA2KhTBWS3pxVnCZ6eScAuNDG3":{
"rating":5,
"timestamp":1.477955566836665E9
}
}
}

If your venues variable is a JSON-like object as in example, you can use the standart json library to work with it:
import json
dict_data = json.loads(venues)
print dict_data['latitude']
Btw, it's a bad style of development - to overwrite built-in Python funuctions. In your example you're overwriting dict(dict is a default Python type-object)

Related

node.js correct extending of json objects

I'm currently using node-ews in a project to access an Exchange Web Server via node.js. Now i ran into a weird problem. To run for example a "CreateItem" request, which can be an E-Mail or Appointment for example, I'm giving the function the arguments as a json similar to this
var args = {
"attributes" : {
"SendMeetingInvitations" : "SendToAllAndSaveCopy"
},
"SavedItemFolderId": {
"DistinguishedFolderId": {
"attributes": {
"Id": "calendar"
}
}
},
"Items" : {
"CalendarItem" : {
"Subject" : "",
"Body" : {
"attributes" : {
},
"$value" : ""
},
"ReminderIsSet" : "true",
"ReminderMinutesBeforeStart" : "30",
"Start" : "",
"End" : "",
"IsAllDayEvent" : "false",
"LegacyFreeBusyStatus" : "Busy",
"Location" : ""
}
}
};
As the REST-API I'm writing will receive Attributes like Subject, Start, End etc. I initially stripped out those out of the JSON and would define them later like
args.Items.CalendarItem.Subject = req.body.Subject;
Oddly this will make the internal validation of node-ews fail and tell me that CalendarItem has an invalid Child Subject. If i leave Subject als an empty string in the initial args and later change it set it to req.body.Subject it works just fine.
My question is this: Is the Object somewhat different if I later add attributes and if yes is there a way to do it right? Because I don't think its the best way to have a bunch of empty Attributes in my Object if they aren't used and define standard values for all of them even if api won't require them to be sent.
Would great if someone knew the answer. Hope i could clarify what the problem is
Ok,
so the problem seems to be this. Internally the JSON "object" seems to have an order based on the order the variable is defined. in JavaScript this is no problem. But when the xml is parsed, the tag that was defined last will also be at the end of the xml so if you had
<someTag>
<variable2 />
<variable3 />
</someTag>
and you add variable1 to your json by someTag.variable1 = x in the end the xml will look like this after beeing parsed by node-ews
<someTag>
<variable2 />
<variable3 />
<variable1 >x</variable1>
</someTag>
Now unfortunately the exchange web server seems to be picky about the order of the xml tags. so when you build your json be sure to use the direct order. Changing content of the json later will not affect the order.

Using JSON in ColdFusion application

I have a website that has a front-end view for non-registered users and then a portal view for registered users.
I am trying to re-vamp the product navigation, wanting to make it easily maintainable for adding/removing links I want this to be in JSON format.
I am using Mura CMS with ColdFusion.
Probably a fairly simple thing I am trying to do but cannot find any examples online.
I have my JSON data as below:
{
"category" : [
{
"name" : "digital stickers",
"products" : [
{
"name" : "round digital stickers",
"urlPublic" : "index.cfm/digital-stickers/round-stickers",
"urlPortal" : "tab=round digital stickers"
},
{
"name" : "square digital stickers",
"urlPublic" : "index.cfm/digital-stickers/square-stickers",
"urlPortal" : "tab=square digital stickers"
}
]
},
{
"name" : "Litho stickers",
"products" : [
{
"name" : "round litho stickers",
"urlPublic" : "index.cfm/litho-stickers/round-stickers",
"urlPortal" : "tab=round litho stickers"
},
{
"name" : "square litho stickers",
"urlPublic" : "index.cfm/litho-stickers/square-stickers",
"urlPortal" : "tab=square litho stickers"
}
]
}
]
}
As you can see I have the category name, which I will use to determine the 'Digital Stickers' and 'Litho Stickers'. I will then loop through the data to pull out the different products names and depending if portal user or public user will take the data to insert into the URL.
To get started I just need to know how to link this into my ColdFusion application. Not a massive ColdFusion Guru yet, more into my JavaScript languages, so any help here would be highly appreciated.
From there I should be good to go.
Just in case that is a bit vague, like html documents link the stylesheet with a tag - how do you link the JSON to the ColdFusion document? Is it like including a ?
After searching around for a while I found a good example on the help.adobe website.
This line of code accesses the JSON data and pulls it in for use
<!--- Get the JSON Feed --->
<cfhttp url="http://localhost:8500/project/JSON_FILE.json">
After that I Deserialized it with
<cfset cfData=DeserializeJSON(theData)>
Then to test I had everything coming back correctly I used a cfdump
<cfdump var="#theData#">
I wanted to spit out only specific data so I did a cfloop to loop through the data array
<h2>Categories</h2>
<cfloop array="#dataArray#" index="elem">
<!--- print out value for demo purposes --->
<cfoutput>
<h3>#elem.name#</h3>
</cfoutput>
</cfloop>
This printed out 'Digital Stickers' and 'Litho Stickers' as expected.
My resources were Adobe Help - getting and deserializing the JSON and Experts Exchange - Loop over deserialized JSON.

Getting fewer/matching objects from json file

My json file looks like this:
[
{
"id" : "1",
"type" : "hardware"
},
{
"id" : "2",
"type" : "software"
}
]
Now when I run following code :
$http({
method: 'get',
url: '/tools.json'
}).success(function(data, status, headers, config) {
///whatever
})
I get these two objects for rederning via ng-repeat, that's fine.
Now, I want to create filters in my app, like display only "Hardware" or "Software", for this, which is the best way to achieve this, is there a way where I can just get Hardware typed objects from JSON itself? (querying JSON and get matching objects) and how can I do that? What should I change in code in-order to do this or should I use Angular filters to render Hardware types after getting entire JSON.
I don't have much experience in Angular, let me know if there is any other way I can achieve what I want.
Thanks in advance.
It's your choice completely.
Ideally, your backend should be returning the JSON filtered by the query.
If you want instant-responsiveness, you may use Angularjs's filters to do the filtering for you on the same data which you'd fetch once from the server. This also has an added benefit of doing full-text search, which is really neat.
If you just want to filter the JSON data, you could use the reduce method as follows:
var hardware = data.reduce(function(result, current) {
if(current.type === 'hardware') {
result.push(current);
}
return result;
}, []);
Fiddle available here.
The ideal place for this filtering would be on backend, given the type. But for some reason, if you want to do this on browser, you can use a simple for loop to filter objects with type hardware. A cleaner way of doing this would be with underscore. Include underscore source file in your project and do _.filter function to filter the objects you want. You can read more about filter function here: http://underscorejs.org/#filter

Issue with parsing JSON flat file in PhantomJS (NO jquery, raw javascript please)

So here is the issue. I have a straight export from mongodb collection as json flat file. I am trying to get my phantomjs app to read and parse the flat file from MongoDB and convert it into an object for phantomjs to parse. For some reason I cannot parse the JSON string normally.
(note: NO jQuery solutions. This needs to be raw javascript)
Here is my flat file from mongodb. It seems fine:
{ "host" : "www.myfoxphilly.com", "path" : "/category/233430/entertainment", "created_at" : { "$date" : 1375199393295 }, "_id" : { "$oid" : "51f7e0a1dc12a13510000002" } }{ "host" : "www.news9.com", "path" : "/category/112032/news", "created_at" : { "$date" : 1375285798173 }, "_id" : { "$oid" : "51f9322668ee1e660c000001" } }{ "host" : "www.myfoxphilly.com", "path" : "/category/233430/entertainment", "created_at" : { "$date" : 1375285823602 }, "_id" : { "$oid" : "51f9323f68ee1e660c000002" } }
Here is the config file that is attempting to parse the above JSON flat file
var fs = require('fs');
var data = fs.read('configData.json');
var newdata = JSON.stringify(data);
var dataobj = eval("["+newdata+"]");
console.log(typeof(newdata));
exports.tests = dataobj;
// Sample object (works fine like this):[{path:'/category/112043/sports' ,host:'www.newson6.com'}];
exports.getFileName = function(test,local) {
return 'results/' + test.host.replace(/\./g,'-').replace(/\:[0-9]+/,'').replace('-com','').replace('www-','') + test.path.replace(/\//g,'-').replace(/\?clienttype=/g, "clienttype") + ((local) ? '-locl' : '-prod')
}
So when I run phantom, I get no data. That JSON becomes one single object, instead of the object example I have in the comment section.
If I just replace the JS common library flat file import and make "data" a string, it works just fine, like so:
var data = '{"host" : "www.myfoxphilly.com", "path" : "/some/path/233409"}';
Is there some sort of issue going on with the js common library file import when I import the JSON in as a string? Help please.
ONCE AGAIN, no jQuery, I will down vote you without looking. I <3 jQuery, but you guys need to realize when it's appropriate to use (i.e. browser-based js).
OMG! You used eval ... :P I'm suprised this question hasn't already been down voted 5 times.
On the real, excellent question.
Your problem, if #DCoder has actually posted an answer, is your JSON. A 'flat file from mongodb' is not necessarily valid JSON. Further, to make it valid you're gonna need to parse the string first:
wrap it in square braces
make sure you have a comma after each data line exported from mongo.
Seriously, eval? Use JSON.parse twice on your converted string.
That should solve it. Everything else looks clean.
(.. eval .. I cant believe this scrub)

Nested Maps in JQuery ajax data to send - how to serialize 'properly'?

var location = { "location" : {
"name" : $("#user_loc_name").val(),
"street_address" : $("#user_loc_street_address").val(),
"city" : $("#user_loc_city").val(),
"province" : $("#user_loc_province").val(),
"country" : $("#user_loc_country").val(),
"postal_code" : $("user_loc_postal_code").val(),
"public" : $("#user_loc_public").attr('checked')
}};
( ... )
$.post(url, location, success_callback);
The reason I need this 'nested' map is because I'm sending this to my rails backend, and I'm hoping I can make a simple update _ attributes(params[:location]) in the controller. Unfortunately, with this solution I get Parameters:
{"location"=>"[object Object]", ...}
Not what I'm hoping for. I'm hoping for:
{"location"=> {"name" => "valforname", "street_address" => "valforstreetadress", ...}, <other params>...}
If I get rid of the 'nesting' and just send the inner map it works fine, but each attribute shows up separately in the params hash and it's just cumbersome and messy. If I could get the whole map nested under a key of "location" it would be much nicer.
Have a look at this:
Serializing Objects in Javascript
jQuery does not support JSON serializing OOTB. Try any number of libraries. Here's the standard one:
<script src="http://www.json.org/json2.js"></script>
Your code then looks like:
$.post(url, JSON.stringify(location), success_callback);

Categories