How to convert this array of strings to array object - javascript

I ma having this string returned from my C# code. I need to implement Google Maps. How d i convert this into array.
String
var array = [["Andover - Wyevale Garden Centre","Concession A","Andover Garden Centre","Salisbury Road","Andover","SP11 7DN","01264 710114","14.9 miles","51.1998552","-1.5111393"],
["Portsmouth - Gunwharf Quays","Unit 29","Gunwharf Quays","Portsmouth","Hampshire","PO1 3TZ","02392 819558","20.8 miles","50.7963663","-1.1065603"],
["Chichester","83 North Street","Chichester","West Sussex","PO19 1LQ","01243 380058","25.9 miles","50.837269","-0.77846"],
["Newport - Isle of Wight","117/119 High Street","Newport","Isle of Wight","PO30 1TP","01983 527485","27.1 miles","50.700399","-1.294872"],
["Guildford","20-21 North Street","Guildford","Surrey","GU1 4AF","01483 456978","29.8 miles","51.2369881","-0.5731617"]]
i dont know but when i do array[1][0] it should return "Portsmouth" in chrome console BUT it is coming as undefined.
I suspect array variable is identified as string and not array.
when i do array[0][4] i get "A" as output.
Please help

use this .. this will running on my side .
var array = '[["d","ddd","sadasd","Salisbury Road","Andover","SP11 7DN","01264 710114","14.9 miles","51.1998552","-1.5111393"],["Portsmouth - Gunwharf Quays","Unit 29","Gunwharf Quays","Portsmouth","Hampshire","PO1 3TZ","02392 819558","20.8 miles","50.7963663","-1.1065603"],["Chichester","83 North Street","Chichester","West Sussex","PO19 1LQ","01243 380058","25.9 miles","50.837269","-0.77846"],["Newport - Isle of Wight","117/119 High Street","Newport","Isle of Wight","PO30 1TP","01983 527485","27.1 miles","50.700399","-1.294872"],["Guildford","20-21 North Street","Guildford","Surrey","GU1 4AF","01483 456978","29.8 miles","51.2369881","-0.5731617"]]'
var arrayObj = JSON.parse(array)
console.log(arrayObj)
console.log(arrayObj[1][0])
// returns---
Portsmouth - Gunwharf Quays

OK try this:
var array = [["Andover - Wyevale Garden Centre","Concession A","Andover Garden Centre","Salisbury Road","Andover","SP11 7DN","01264 710114","14.9 miles","51.1998552","-1.5111393"],
["Portsmouth - Gunwharf Quays","Unit 29","Gunwharf Quays","Portsmouth","Hampshire","PO1 3TZ","02392 819558","20.8 miles","50.7963663","-1.1065603"],
["Chichester","83 North Street","Chichester","West Sussex","PO19 1LQ","01243 380058","25.9 miles","50.837269","-0.77846"],
["Newport - Isle of Wight","117/119 High Street","Newport","Isle of Wight","PO30 1TP","01983 527485","27.1 miles","50.700399","-1.294872"],
["Guildford","20-21 North Street","Guildford","Surrey","GU1 4AF","01483 456978","29.8 miles","51.2369881","-0.5731617"]];

Try removing your encompassing double quotes and include a terminating semi-colon ;...
var array = [["Andover - Wyevale Garden Centre","Concession A","Andover Garden Centre","Salisbury Road","Andover","SP11 7DN","01264 710114","14.9 miles","51.1998552","-1.5111393"],
["Portsmouth - Gunwharf Quays","Unit 29","Gunwharf Quays","Portsmouth","Hampshire","PO1 3TZ","02392 819558","20.8 miles","50.7963663","-1.1065603"],
["Chichester","83 North Street","Chichester","West Sussex","PO19 1LQ","01243 380058","25.9 miles","50.837269","-0.77846"],
["Newport - Isle of Wight","117/119 High Street","Newport","Isle of Wight","PO30 1TP","01983 527485","27.1 miles","50.700399","-1.294872"],
["Guildford","20-21 North Street","Guildford","Surrey","GU1 4AF","01483 456978","29.8 miles","51.2369881","-0.5731617"]];

Related

I need help. Seems like a basic tool that I cannot seem to find

Lets say I have some random text info that I have collected from subpar sources. The text consists of something as follows:
1st Floor - aklsl;asndgjasblgkbaskdbfjkabsdlkfbjla 2nd Floor - infoinfofino theoreticalinfo yasddadas 3rd Floor - more random stuff relevant to this floor, no consistency in the data etc.
and I want to put this into a string. So:
var string = "1st Floor - aklsl;asndgjasblgkbaskdbfjkabsdlkfbjla 2nd Floor - infoinfofino theoreticalinfo yasddadas 3rd Floor - more random stuff relevant to this floor, no consistency in the data etc.";
How do I split the string into an array based on the special characters "1st" "2nd" "3rd" "4th" etc. because there is no numerical pattern to the info after each floor.
I was thinking
var newString = string.split("1st" || "2nd" || "3rd");
console.log(newString);
You can use split with regex:
var string = "1st Floor - aklsl;asndgjasblgkbaskdbfjkabsdlkfbjla 2nd Floor - infoinfofino theoreticalinfo yasddadas 3rd Floor - more random stuff relevant to this floor, no consistency in the data etc.";
var result = string.split(/(1st|2nd|3rd)/);
console.log(result);
Maybe you want a regex that could obtain n Floors instead of only some of them (1st, 2nd and 3rd)
var string = "1st Floor - aklsl;asndgjasblgkbaskdbfjkabsdlkfbjla 2nd Floor - infoinfofino theoreticalinfo yasddadas 3rd Floor - more random stuff relevant to this floor, no consistency in the data etc.";
var result = string.split(/[\d]+\w+\sFloor\s[-]\s/).filter(item => item.length > 1);
console.log(result);

Angular.js format json data

"[{rest_id:"2", cate_id:"4", rest_name:"Samraat Curry Hut", adress:"6275 Jarvis Ave, Newark, CA 94560", city:"Newark", state:"New Jersey", country:"US", email_id:"", rest_url:"Samraat-Curry-Hut", phone_no:"(510) 745-7000", rest_image:"http://www.mealhi5.com/images/restaurant/Samraat-Curry-Hut.jpg"}]"
top array my result but my required bottom array add double quote key
rest_id to "rest_id" all key add double quote("")
my required array
This Angular JS
first JSON is my input and output second array
[{"rest_id":"2", "cate_id":"4", "rest_name":"Samraat Curry Hut", "adress":"6275 Jarvis Ave, Newark, CA 94560", "city":"Newark", "state":"New Jersey", "country":"US", "email_id":"", "rest_url":"Samraat-Curry-Hut", "phone_no":"(510) 745-7000", "rest_image":"http://www.mealhi5.com/images/restaurant/Samraat-Curry-Hut.jpg"}]
Take a look at JSON.parse (if you want to use it as a JSON object)
var foo = JSON.parse("[{rest_id:"2", ...}]");
You can do one thing use regular expressing in that case:-
var a= JSON.stringify([{"rest_id":"2", "cate_id":"4", "rest_name":"Samraat Curry Hut", "adress":"6275 Jarvis Ave, Newark, CA 94560", "city":"Newark", "state":"New Jersey", "country":"US", "email_id":"", "rest_url":"Samraat-Curry-Hut", "phone_no":"(510) 745-7000", "rest_image":"http://www.mealhi5.com/images/restaurant/Samraat-Curry-Hut.jpg"}]);
a=a.replace(/"(\w+)"\s*:/g, '$1:');
Fiddle

Custom sorting using orderBy directive of Angular

Below is the sort criteria from A to Z:
1) special characters
2) numbers
3) alphabet
For example:-
$scope.cards = ["815 BRAZOS ST AUSTIN TX 78701","7745 CHEVY CHASE DR AUSTIN TX 78752","701 BRAZOS ST AUSTIN TX 78701","555 ROUND ROCK WEST DR ROUND ROCK TX 78681","400 W 15TH ST AUSTIN TX 78701"]
Expected result after sorting:-
400 W 15TH ST AUSTIN TX 78701
555 ROUND ROCK WEST DR ROUND ROCK TX 78681
701 BRAZOS ST AUSTIN TX 78701
815 BRAZOS ST AUSTIN TX 78701
7745 CHEVY CHASE DR AUSTIN TX 78752
I want to achieve this using Angular orderBy filter. As in JS custom sort function, we got two arguments and by manipulating that we can return >0, <0 and 0 to achieve custom sort.
My Attempt
<div ng-controller="MyCtrl">
<ul ng-repeat="card in cards | orderBy:myValueFunction">
<li>{{card}}</li>
</ul>
</div>
JS
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.cards = ["815 BRAZOS ST AUSTIN TX 78701","7745 CHEVY CHASE DR AUSTIN TX 78752","701 BRAZOS ST AUSTIN TX 78701","555 ROUND ROCK WEST DR ROUND ROCK TX 78681","400 W 15TH ST AUSTIN TX 78701"]
$scope.myValueFunction = function(card,card1) {
console.log(card);
console.log(card1);
return card;
}
}
JSfiddle link
Thanks
According to documentation your function should return a value, that would be used for sorting using standard comparison operators (<,>,=).
So in your case your function should return an value, that would determine sorting. For your case, you need to put some advanced logic to produce such value.
For simples example (sort by first numbers), you get:
$scope.myValueFunction = function(card) {
return card.split(' ')[0]|0;
}
At least you'll have what you've requested in your small sample, see here: http://jsfiddle.net/zjvsu/529/
UPDATED
If you want to compare two values just like standard javascript sort custom function then you will have to use your own filter which returns sorted array.

javascript json uncaught syntaxerror unexpected token illegal

I am getting server response json with special character, How can i remove this special charecter from it. It tried replace() but its not working. My json sample is here
{
"#tag":"1013170",
"#title":"Holman Rd & Trestle Glen Rd",
"#lat":"37.8067794",
"#lon":"-122.2325773",
"#stopId":"52750"
}
try something like this
var str = '{"#tag":"1013170","#title":"Holman Rd & Trestle Glen Rd","#lat":"37.8067794","#lon":"-122.2325773","#stopId":"52750"}';
console.log(str.replace(/#/g,''));
//will give you
{"tag":"1013170","title":"Holman Rd & Trestle Glen Rd","lat":"37.8067794","lon":"-122.2325773","stopId":"52750"}
By the way your json is valid
var json ={"#tag":"1013170","#title":"Holman Rd & Trestle Glen Rd"};
//var json_obj = $.parseJSON(json);//don't do this because it already json.
console.log(json.#tag); // don't use this way
console.log(json['#tag']);// instead try this way
You can't change a property name, you have to add the value with a new name and delete the old property:
object = {
"#tag":"1013170",
"#title":"Holman Rd & Trestle Glen Rd",
"#lat":"37.8067794",
"#lon":"-122.2325773",
"#stopId":"52750"
}
for (var property in object) {
if (object.hasOwnProperty(property)) {
object[property.slice(1)]=object[property];
delete object[property];
}
}
console.log(object) will now give you
{tag: "1013170", title: "Holman Rd & Trestle Glen Rd", lat: "37.8067794", lon: "-122.2325773", stopId: "52750"}
Finally i read the json with this line.
result['#tag']
Its simple you can read json from '.' notation and from [], the second one reads special character as well.

Parsing JSON with JSON.NET

I have a JSON string:
{"responseData":
{"results": [
{"GsearchResultClass": "GblogSearch",
"title":"\u003cb\u003eParis Hilton\u003c/b\u003e shops at Sydney Michelle boutique in the Beverly Glen \u003cb\u003e...\u003c/b\u003e",
"titleNoFormatting":"Paris Hilton shops at Sydney Michelle boutique in the Beverly Glen ...",
"postUrl":"http://www.celebrity-gossip.net/celebrities/hollywood/paris-hilton-sydney-michelle-stockup-215844/",
"content":"\u003cb\u003eParis Hilton\u003c/b\u003e shops at Sydney Michelle boutique in the Beverly Glen Mall - \u003cb\u003eParis Hilton\u003c/b\u003e: Sydney Michelle Stockup.",
"author":"The Gossip Girls at (c) gossipgirls.com",
"blogUrl":"http://www.celebrity-gossip.net/",
"publishedDate":"Tue, 23 Feb 2010 22:26:00 -0800"
},
{"GsearchResultClass":"GblogSearch",
"title":"\u003cb\u003eParis Hilton\u003c/b\u003e having wardrobe woes as she met with her lawyer",
"titleNoFormatting":"Paris Hilton having wardrobe woes as she met with her lawyer",
"postUrl":"http://www.celebrity-gossip.net/celebrities/hollywood/paris-hiltons-wardrobe-woes-215855/",
"content":"\u003cb\u003eParis Hilton\u003c/b\u003e having wardrobe woes as she met with her lawyer - \u003cb\u003eParis Hilton's\u003c/b\u003e Wardrobe Woes.",
"author":"The Gossip Girls at (c) gossipgirls.com","blogUrl":"http://www.celebrity-gossip.net/",
"publishedDate":"Wed, 24 Feb 2010 11:07:56 -0800"
},
{"GsearchResultClass":"GblogSearch",
"title":"HOT GALLERY: \u003cb\u003eParis Hilton\u003c/b\u003e Turns Her Frown Upside Down | OK \u003cb\u003e...\u003c/b\u003e",
"titleNoFormatting":"HOT GALLERY: Paris Hilton Turns Her Frown Upside Down | OK ...",
"postUrl":"http://www.okmagazine.com/2010/02/hot-gallery-paris-hilton-turns-her-frown-upside-down/",
"content":"\u003cb\u003eParis Hilton\u003c/b\u003e kept her game face on yesterday as she headed to a meeting in Hollywood. The socialite maintained her composure, but eventually cracked a smile, 201002.",
"author":"Brittany Talarico",
"blogUrl":"http://www.okmagazine.com/",
"publishedDate":"Wed, 24 Feb 2010 07:57:10 -0800"
},
{"GsearchResultClass":"GblogSearch",
"title":"Love It Or Hate It: \u003cb\u003eParis Hilton\u003c/b\u003e | ImNotObsessed.com",
"titleNoFormatting":"Love It Or Hate It: Paris Hilton | ImNotObsessed.com",
"postUrl":"http://www.imnotobsessed.com/2010/02/24/love-it-or-hate-it-paris-hilton",
"content":"tweetmeme_url \u003d \"http://www.imnotobsessed.com/2010/02/24/love-it-or-hate-it-\u003cb\u003eparis\u003c/b\u003e-\u003cb\u003ehilton\u003c/b\u003e\";tweetmeme_element_id \u003d '#tweetmeme-widget-139430e62dc37d7a2aa71840d6444572';That's some dress \u003cb\u003eParis Hilton\u003c/b\u003e was seen wearing while shopping in ...",
"author":"Vera",
"blogUrl":"http://www.imnotobsessed.com/",
"publishedDate":"Wed, 24 Feb 2010 10:44:28 -0800"
}],
"cursor": {
"pages": [
{"start":"0","label":1},
{"start":"4","label":2},
{"start":"8","label":3},
{"start":"12","label":4},
{"start":"16","label":5},
{"start":"20","label":6},
{"start":"24","label":7},
{"start":"28","label":8}],
"estimatedResultCount":"8035445",
"currentPageIndex":0,
"moreResultsUrl":"http://blogsearch.google.com/blogsearch?oe\u003dutf8\u0026ie\u003dutf8\u0026safe\u003dactive\u0026source\u003duds\u0026start\u003d0\u0026hl\u003den\u0026q\u003dParis+Hilton"
}
},
"responseDetails": null,
"responseStatus": 200}
ed. note: line breaks added for readability
and I'm using Json.NET to parse it, however its giving me a null
this is my code:
JObject o = JObject.Parse(json); // <- where json is the string above
string name = (string)o["responseData"];
BUT its giving me this error :
Can not convert {null} to String.
Using Json.Net, you can deserialize the object like this:
BlogSearch search = JsonConvert.DeserializeObject<BlogSearch>(content);
You would define the BlogSearch object like this:
[JsonObject(MemberSerialization.OptIn)]
public class BlogSearch
{
[JsonProperty(PropertyName = "responseData")]
public BlogSearchResponse SearchResponse { get; set; }
}
You keep defining objects until you have all the ones you are interested in.
Have you tried things like?
string gsearchresultclass= (string)o["responseData"]["results"][0]["GsearchResultClass"];
string title= (string)o["responseData"]["results"][0]["title"];
string titlenoformat= (string)o["responseData"]["results"][0]["titleNoFormatting"];
string url = (string)o["responseData"]["results"][0]["postUrl"];
string content = (string)o["responseData"]["results"][0]["content"];
string author = (string)o["responseData"]["results"][0]["author"];
string blogurl = (string)o["responseData"]["results"][0]["blogUrl"];
string date = (string)o["responseData"]["results"][0]["publishedDate"];
What exactly are you trying to get into the name variable?
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx
Its a good alternative to your method, that I would recommend...
Hope that helps...
If you're posting your JSON object raw to the Web API then you will run into this problem. The Deserializer is expecting an actual string and not an object or an array. Because it is using a JsonMediaTypeFormatter, it won't know how to translate what is being passed to it.
You need to do the following to avoid the null:
public HttpResponseMessage postBlogSearch([FromBody] JToken json){
var jsonResult = JObject.Parse(json.ToString());
var name = jsonResult["responseData"].ToString();
}
For more information see this article.

Categories

Resources