Construct JSON object from array on client-side? - javascript

I have a string array like this:
['QWJvdXQ=','SG93IGl0IFdvcmtz','SG9tZQ==','Q29udHJpYnV0ZQ==','Q29udGFjdA==']
What I want to do, is turn it into something like this:
[
{
"id" : "QWJvdXQ=",
"url": "about.html"
},
{
"id" : "SG93IGl0IFdvcmtz",
"url": "how_it_works.html"
},
{
"id" : "SG9tZQ==",
"url": "index.html"
},
{
"id" : "Q29udHJpYnV0ZQ==",
"url": "contribute.html"
},
{
"id" : "Q29udGFjdA=="
"url": "contact.html"
}
]
The attributes aren't the focus -- what I'm basically trying to do is make each item in the array an object with the value as an value of an attribute, and add another (or more) key-value pairs into those objects.
Right now, I'm trying to do this on the client-side, using jQuery and JS. I also am running node.js, so if this is easier to do on the server-side I'm open to any suggestions. Any help is appreciated!

What you need
JSON.stringify
Array.prototype.map
window.atob
all together;
JSON.stringify(
['QWJvdXQ=','SG93IGl0IFdvcmtz','SG9tZQ==','Q29udHJpYnV0ZQ==','Q29udGFjdA=='].map(
function (e) {
return {
'id': e,
'url': atob(e).toLowerCase().replace(/\s/g, '_') + '.html'
}; // I converted the string to URL as I expect you wanted
}
),
0, 4);

Related

Access nested JSON in json2html

I'm using json2html to create a report for a given JSON file. I was wondering what exactly the syntax is to access nested objects and their fields. For example,
var jsonData = {
"field1": "value1",
"field2": "value2",
"nestedObject": {
"nestedField1": "nestedValue1",
"nestedField2": "nestedValue2"
}
}
What's the syntax to access "nestedField1"? The transform that I'm using is,
var transform = [
{tag : "h1", html : "${field1}"},
{tag : "article", html : "${field2}"},
{tag : "article", html : "${nestedObject}" }
]
The last statement html : "${nestedObject}" returns [Object object] as expected. But, I can't seem to access its fields.
"${nestedObject.nestedField1}"
This should do the trick.
Just like how you'd access it in JS:
jsonData.nestedObject.nestedField1
I should have tried everything that seemed intuitive.
The simple way is,
{ tag : "article", html : "the first nested field is ${nestedObject.nestedField1}" }

How to get data from json in order to save them in database?

I am beginner in Javascript/jQuery and I am working on an interface made with KnockoutJS, so I have several models. I would like to save all the data in the database but I don't know how to do it.
I started with :
self.save = function() {
var data = ko.toJS(self);
var test = ko.toJSON(self);
console.log(test);
}
$.ajax({
url: "myURL",
data: {'carrier': data.carrier},
type: "POST",
});
and this is the result of the console.log :
{"id":1,"carrier":"1","Settings":[{"id":1,"price":{"id":1,"DeliveryStandard":"3.00","DeliveryExpress":"6.00","Details":{"id":1,"Standard":[{"id":1,"fromPrice":0,"maxPrice":"45.000"}],"Express"[{"id":1,"fromPrice":0,"maxPrice":"66.000"}]}}}}]}
I can get the value of carrier by using data.carrier but I don't know how to get the other data like DeiveryStandard, DeliveryExpress, fromPrice, maxPrice ...
Have you got an idea?
Thanks you in advance, and sorry if my question is silly!
If you format your JSON into a more readable format, with indenting, it makes it a lot easier to understand:
(though it should be noted that it is only technically JSON while in a string format, outside of that it is just a standard javascript object)
{
"id":1,
"carrier":"1",
"Settings":[
{
"id":1,
"price": { "id":1,
"DeliveryStandard":"3.00",
"DeliveryExpress":"6.00",
"Details": { "id":1,
"Standard": [{"id":1,
"fromPrice":0,
"maxPrice":"45.000"
}],
"Express" //Missing semi-colon
[{"id":1,
"fromPrice":0,
"maxPrice":"66.000"
}]
}
}
}}//One too many closing braces
]
}
First thing to note is you have 2 syntax errors, highlighted above with comments. So fix them first! (Though I wonder if they are typos as you seem to have it working at your end)
Then we can look at the structure tree to work out where the values you want are...
DeiveryStandard and DeliveryExpress are both properties of an object assigned to price, which it a property of the first item in the Settings array. So you can access them like so:
var DeliveryStandard = data.Settings[0].price.DeliveryStandard;
var DeliveryExpress= data.Settings[0].price.DeliveryExpress;
fromPrice and maxPrice are found multiple times, in both Standard and Express items. So you need to decide what version you need. If you want Standard then you can get the first item of the Standard array like so:
var standardObject = data.Settings[0].price.Details.Standard[0];
Which you can then access the properties of like:
var fromPrice = standardObject.fromPrice;
var maxPrice = standardObject.maxPrice;
I am sure you can work out how to get the Express version of the same data!
From what you seem to have been able to work out on your own, I think your problem is not knowing how to deal with the arrays. Note that arrays are defined with square brackets [], and elements within an array should be accessed with a zero-based index, for example: array[0] for the first element, and array[1] for the second element.
This should work.
console.log(data.Settings[0].price.DeliveryStandard);
Fixed some errors in your JSON.
var j = {
"id" : 1,
"carrier" : "1",
"Settings" : [{
"id" : 1,
"price" : {
"id" : 1,
"DeliveryStandard" : "3.00",
"DeliveryExpress" : "6.00",
"Details" : {
"id" : 1,
"Standard" : [
{
"id" : 1,
"fromPrice" : 0,
"maxPrice" : "45.000"
}
],
"Express": [
{
"id" : 1,
"fromPrice" : 0,
"maxPrice" : "66.000"
}
]
}
}
}
]
};
alert(j.Settings[0].price.DeliveryStandard);
alert(j.Settings[0].price.DeliveryExpress);
alert(j.Settings[0].price.Details.Standard[0].fromPrice);
alert(j.Settings[0].price.Details.Standard[0].maxPrice);

twitter typeahead 0.9.3 remote return URL and json object

in bootstrap 2, I used the following code to post a json object,
$('#typeahead').typeahead({
source: function (query, process) {
var URL = 'http://localhost:8080/autocomplete/search/';
var query = {"t:jsonStringField": {
"name": "model",
"value": "fusion"
},
"t:jsonStringFilter": [
{"name": "year","value": "2009"},
{"name": "make","value": "ford"}
]
};
return $.getJSON(URL,
{ query: JSON.stringify(query)},
function (data) {
return process(data);
});
}
});
Now in twitter tyeahead 0.9.3 they have done away with the source concept and moved to a remote concept, but unfortunately I do no know how to work with it.
$(".typeahead").typeahead({
remote : {
url: 'http://localhost:8080/autocomplete/search/',
replace: function(uri, query) {
var query = {"t:jsonStringField": {
"name": "model",
"value": "fusion"
},
"t:jsonStringFilter": [
{"name": "year","value": "2009"},
{"name": "make","value": "ford"}
]
};
return uri + JSON.stringify(query);
},
filter: function(response) {
return response.matches;
}
return process(resultList);
}
}
Unfortunately it doesn't work, how do I just post the JSON object rather than appending it to the string? Thanks.
In your original code you use $.getJSON. This will send a request (and expects json as result) to: http://localhost:8080/autocomplete/search/?query=%7B%22t%3AjsonStringField%22%3A%7B%22name%22%3A%22model%22%2C%22value%22%3A%22fusion%22%7D%2C%22t%3AjsonStringFilter%22%3A%5B%7B%22name%22%3A%22year%22%2C%22value%22%3A%222009%22%7D%2C%7B%22name%22%3A%22make%22%2C%22value%22%3A%22ford%22%7D%5D%7D
To do the same for Twitter's Typeahead call your replace function of your remote data should return a valid url. In your function the ?query= part of the url is missing.
You will have to set: url: 'http://localhost:8080/autocomplete/search/?query=',
You also will have to urlencode you json input maybe.
Note: you will not need the line return process(resultList); You will have to use the filter function to convert your json results to valid data:
The individual units that compose datasets are called datums. The
canonical form of a datum is an object with a value property and a
tokens property.
you could use templates to style your dropdown results, see: http://twitter.github.io/typeahead.js/examples/
By default, the dropdown menu created by typeahead.js is going to look
ugly and you'll want to style it to ensure it fits into the theme of
your web page.
You will need the additional CSS from https://github.com/jharding/typeahead.js-bootstrap.css to style the default dropdown for Bootstrap.

formatting a json object

Im trying to use json to store some values from a page and then access these values/variables
later in a php file. Now the thing is that I'm new to json and javascript in general and Im
struggling for hours to find a solution to a problem that might be stupidly simple for you
guys who have experience in this:
Now I have this:
var invoice_data = {
"client":[
{
"client-name" : "",
"client-address" : "",
"client-address-2" : "",
"client-city-state" : "",
"client-country" : ""
}
],
"shoppingcart":[
{
"1" : {"item-name":"", "qty":"", "price":"", "discount":"", "subtotal":""}
}
],
};
So is this inheritance thing im not really getting. So just as I've created "client" object
im creating "shoppingcart", now the thing is that when user orders more than an item there should be created another sub-object that would store it's details too.So im assuming like:
"shoppingcart":[
{
"1" : { "item-name":"", "price":"", "discount":"" }
"2" : { "item-name":"", "price":"", "discount":"" }
}
],
So when I console.log(invoice_data.shoppingcart); I get the "shoppingcart" object, but I
cant access invoice_data.shoppingcart.1 or invoice_data.shoppingcart.2, is there any way I can access 1 or 2 sub-object just as access invoice_data.shoppingcart or invoice_data.client?
Thank you.
Edit: I can access it as an array, im not interested in that option. Ideally i'd like to access the sub-object via it's name.
Remove the array syntax:
Change this:
"client":[
{
"client-name" : "",
"client-address" : "",
"client-address-2" : "",
"client-city-state" : "",
"client-country" : ""
}
]
to this:
"client": {
"client-name" : "",
"client-address" : "",
"client-address-2" : "",
"client-city-state" : "",
"client-country" : ""
}
The same goes for shopping cart.
You can't access invoice_data.shoppingcart.1 because 1 is not a valid Javascript variable name. If the key for an object isn't a valid variable name, you have to use array notation: invoice_data.shoppingcart[1].
EDIT: I didn't see it, but as Matt pointed out, you must remove the array syntax as well.
Your shopping_cart is an array.
You don't want:
shopping_cart : {
1 : { name : "...", price : "..." },
2 : { ... }
}
You want:
shopping_cart : [
{ name : "..." },
{ ... }
]
Then you would access that by saying:
shopping_cart[0].name;
shopping_cart[0].price;
Et cetera.
Arrays also start at 0 and not 1.
And this isn't inheritance: it's just a collection of things.

mapping deep json

How to mapping this json ?, i have been trying with multiple argument on each, but still can't get the data.
{
"data" : {
"after" : "t3_qp79c",
"before" : null,
"children" : [ {
"data" : { "url" : "http://imgur.com/c0COJ" },
"kind" : "t3"
} ],
"modhash" : ""
},
"kind" : "Listing"
}
My javascript code
$.getJSON(reddit_api_url,function(data) {
$.each(data.children['data'], function(i, reddit) {
// Uncomment line below to show tweet data in Fire Bug console
// Very helpful to find out what is available in the tweet objects
// console.log(reddit);
// Before we continue we check that we got data
console.log(i+' : '+ reddit );
// Build the html string for the current tweet
var tweet_html = reddit.url;
// Append html string to tweet_container div
$('#tweet_container').append(tweet_html);
});
}
Thanks
The data returned has its own data property, so you'd need...
data.data.children[0]['data']
...to get to that innermost data.
If you were iterating the children, then you'd pass that to $.each...
$.each(data.data.children, function(i, obj) {
console.log(obj.data.url);
});

Categories

Resources