Setting object to url in a custom manner - javascript

I am trying to create my own sort of "state" routing and am struggling with the manipulation of the URL. I have all the working parts for saving the state as an object and such, but I need to turn that object into a URL. So for reference, here is what my object looks like :
urlObject =
[
{"module":"module1",
"customUrl":[{"mod1":["1","2"]},{"mod2":["1","2"]}]
},
{"module":"module2",
"customUrl":[{"mod3":["true","false"]},{"mod4":["5","6"]}]
}
]
So right now I am just doing a simple
$location.search(JSON.stringify(urlObject));
To toss it in the URL. It would be neat if there were some way to format that, parse the URL formatting in my own way, so like It would change to like
/module1="module1sobject/module2="module2object"
When I say module2sobject, I mean the customUrl inside that object--so in that case it would be [{"mod1":["1","2"]},{"mod2":["1","2"]}]. I'm wondering if I could get some guidance on how to begin this process of setting and getting the object out of a url like this (specifically for use in my angular controllers).

Related

Rendering JSON key value pairs in ReactJS?

I'm jumping from JS into React. I've searched a bit for some other threads relating to this, but they seem to be too specific, or answering a different question.
I have a local JSON file generated with a python script. It looks something like the following:
[{"hello": 10, "world": 15}]
How could I go about taking the keys and values from that object JSON TEXT and render it through a react component?
I have the file stored in a variable, like:
'var jsonData = require('./data.json');
Of course I can call the data through the console with a log, but if I try to display it through my render function like:
<div>{jsonData}</div>
I get an error noting that "Objects are not valid as a React child(...)".
What would be the proper way to import and display the key value pairs held in my JSON file?
To conver JSON to string, in order to be display, you can use JSON.stringify method:
<div>{JSON.stringify(jsonData)}</div>
Of course you might want to properly format the data with HTML/CSS.

javascript array into object with same key names

I have an unusual problem to solve here. I have an array of Guids
[
"c01f8237-72c8-4fa6-9c53-1915750385aa",
"2c8a471b-c408-436c-81b1-3f3867d8ffb4",
"27a44d46-12bd-4784-ceed-57ada31b0e33"
]
This array has to be transformed into:
{
id: "c01f8237-72c8-4fa6-9c53-1915750385aa",
id: "2c8a471b-c408-436c-81b1-3f3867d8ffb4",
id: "27a44d46-12bd-4784-ceed-57ada31b0e33"
}
I know that shouldn't be done, but unfortunately cannot control the back end part. Any idea?
Thanks
The whole point of a dictionary key is that it uniquely maps to some value. Your desired output attempts to duplicate a key and therefore is neither possible nor does it make sense.
If you're passing this to a backend (as you suggest), then of course you can manually build a string to pass over the wire that duplicates keys in the payload, but you won't be able to actually do it in JavaScript first. You'll have to manually build the string.
Also note that you can call this format whatever you want, but you can't call it JSON and you can't use JSON libraries to build it (because it's not JSON). If your API expects a custom format, then you need to write code to build that custom format.
If all you want is a string just do something like
var str = '{' + idArray.map(function(id) {
return "id: "+id
}).join(',\n')+'}';
I have no idea what mime type you would put on that though since its not valid JSON.

JSON parsing a Titanium.App.Properties string

In an app, made with TideSDK; i assign a global variable (shocking I know) to a the JSON parse of a string stored in Titanium.App.Properties:
var workbookArray = JSON.parse(Titanium.App.Properties.getString('workbookArray'));
workbookArray is an array of objects.
And then on the unloading of a page, I assign Titanium.App.Properties string the value of workbookArray, which may have been changed by whoever has used the app:
Titanium.App.Properties.setString('workbookArray', JSON.stringify(workbookArray));
Each time I open the app, however, I'm told that JSON was unable to parse the first code snippet (initializing workbookArray).
Aside from this issue, I don't expect to use the app Properties API for my storage needs in the longterm, I wish i could use indexedDB with titanium. SQL is an option, but is a little messy when it comes to objects. Any other suggestions for a database solution?
Try getList and setList
http://docs.appcelerator.com/titanium/latest/#!/api/Titanium.App.Properties
What is stored in the list?

Backbone.js Modifying data in model before save

I was wondering how I would go about converting data when I call the set or save methods on a model. Specifically converting the inputted date string to epoch time.
I know I could just convert it in the view, but as far as I know, that wont work very well with my validations.
The model code is here if you are interested.
Thanks for any help!
What I can gather you have two options:
1 Convert them in your view
This means you can roll your own conversions for the view or use something like Backbone.modelbinder to make the conversions for you. Then you have to modify your validate method to accept an epoch date. Personally I would prefer this one, I think that it's suitable for the UI to handle verifying user input's well-formedness and conversion to the right unit and let the model handle validating if the values are within the accepted limits.
2 Convert them in your model
Backbone doesn't offer this out-of-the-box. If you set something to be something, there is no easy way to convert it to something else, especially between validate and set. Basically your best bet would be to roll your own set -function with something like
// Inside the set function
...
if (!this._validate(attrs, options)) return false; // real line in the set func
// insert something like this, after validate you know the values are eligible for conversion
attrs = this.convert(attrs); // a custom func that converts attributes to right units
...
// set continues as usual
Hope this helps!
You can overwrite the sync method in your model:
, sync: function(method, model) {
if(method === 'update'){
// change you model here
}
}
This will be invoke bevor data is send to the backend server. The "method" indecates 'create' or 'update'.
According to the sources, validate is the only callback that is called before set and save. You can to set the values in your validate method directly on the attributes object. Unfortunately you cannot make any changes to attributes at this point.
You can use a plugin like backbone.getters.setters to do this since it looks like it won't be a feature added to backbone.

How to parse JSON dynamically in iOS

We used a third party service and it provides a JS file.
The js file launches an http request and get a json.We parsed the json and got the content we wanted but the json format always changes.
Is there a way to parse the json but do not update our app?
It sounds awful stupid to constantly change schemas, but anyway, maybe you could try having a manifest somewhere in the cloud that translates the latest schema keywords into one your app understands?
Basically, I presume that the info in the JSON is similar (otherwise it wouldn't make sense at all) and only the keywords change. You could have a JSON you constantly update that translates the keywords used in the app into the newest one used by the webservice.
So an example would look like this. Imagine this is the format you are used to when developing the app (this is the one app expects).
{
"name" : "Henri",
"title" : "iOS Developer"
}
Now if the webservice changes it's schema and returns something like this
{
"key1" : "Henri",
"key2" : "iOS Developer"
}
You should have a manifest.json which translates it like this
{
"name" : "key1",
"title" : "key2"
}
I hope you get where I'm going with this, basically you can shift the translation to the cloud, giving you the chance to keep it up to date while app remains the same. So after loading in the translation you can access the data like this
NSString *name = [actualJSON objectForKey: [manifestJSON objectForKey: #"name"]];
The JSON home page has quite a bit of materials on the subject which should allow you to develop your own parser if you wish. There are also some ObjectiveC parsers available down at the bottom of the page.
http://www.json.org/
For this purpose we looked at Cocoa's standard key path infrastructure but weren't particularly happy with how it combines with arrays and dictionaries. In the end I ended up writing my own little key-path lookup thing, essentially like:
- (id)objectAtPath:(NSString *)path inObject:(id)object
{
// accept an input string like key1.key2.key3.index.key4.etc;
// so we'll split on the dots and use each separate component
// to navigate the object graph
NSString *components = [path componentsSeparatedByString:#"."];
for(NSString *component in components)
{
if([object isKindOfClass:[NSDictionary class]])
{
// if this is a dictionary, use this component as
// a key into the dictionary
object = [object objectForKey:component];
}
else
if([object isKindOfClass:[NSArray class]])
{
// if this is an array, use this component
// as an index into the array
NSInteger index = [component integerValue];
// treat out of bounds indices as finding nil
// rather than raising an exception
if(index < 0 || index >= [object count]) object = nil;
else object = [object objectAtIndex:index];
}
}
}
So you might call objectAtPath:#"shoes.4.typeOfLaces" inObject:jsonResult if 'jsonResult' is a dictionary to get the array 'shoes', the dictionary at index 4 in the array and then whatever value that dictionary has for the key 'typeOfLaces'.
The production code actually has some smarter navigation aids, allowing you to say things like "take whichever object in this array of dictionaries has the largest value for the key 'size'" or "take the object with type=large if it exists, otherwise take any object", but exactly what you want to do there will depend on your app and the variability of the schema.
Once you're navigating object graphs by key path, you can just grab the current key paths from a server somewhere, allowing you to change how JSON is navigated on device without submitting a new binary.
The only warning I'd add is to be careful how much functionality you put into your key paths. Apple don't allow fresh code to be downloaded so whatever you do you don't want to end up at anything that Apple could construe as a scripting language, no matter how restricted.

Categories

Resources