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.
Related
I do not have any control over modifying the server endpoint to return a valid JSON.
Endpoint: http://newsrack.in/stories/servelots/iihs_feeds/16.json
sample response data:
`var _nr_metadata = {
site_base_url : "http://newsrack.in",
issue_name : "iihs_feeds",
category_name : "Chikungunya",
listing_url : "/stories/servelots/iihs_feeds/16"
}
var _nr_stories = [
{
title : "Delhi: Changing weather conditions cause 25 per cent rise in dengue cases",
url : "http://indiatoday.intoday.in/story/delhi-changing-weather-conditions-cause-rise-in-dengue-cases/1/1075570.html",
source : "India Today| Must Read",
date : "26.10.2017",
desc : "<a href=\'http://indiatoday.intoday.in/story/delhi-changing-weather-conditions-cause-rise-in-dengue-cases/1/1075570.html?utm_source=rss\'><img src=\'http://media2.intoday.in/indiatoday/images/stories/dengue305_102617022722.jpg\' align=\"left\" hspace=\"2\" height=\"180\" width=\"305\" alt=\"\" border=\"0\"/><\/a>Usually at this time of the year, the virus becomes inactive due to \ntemperature dip. But experts are witnessing the hostile nature of ades \nmosquitoes."
},
{
title : "Waste management bye-laws pending approval of LG: Delhi High Court told",
url : "http://indianexpress.com/article/delhi/waste-management-bye-laws-pending-approval-of-lg-delhi-high-court-told-4906249/",
source : "Delhi – The Indian Express",
date : "25.10.2017",
desc : "<img alt=\"\" border=\"0\" src=\"http://pixel.wp.com/b.gif?host=indianexpress.com&blog=53855017&post=4906249&subd=indianexpressonline&ref=&feed=1\" width=\"1\" height=\"1\" />"
},
{
title : "Alarm bells ringing:194 dengue cases in 2 weeks in district",
url : "http://www.tribuneindia.com/news/ludhiana/alarm-bells-ringing-194-dengue-cases-in-2-weeks-in-district/486718.html",
source : "The Tribune",
date : "25.10.2017",
desc : "Tribune News Service\nLudhiana, October 24\nThe number of dengue cases is rapidly increasing in the district as 194 confirmed cases have been recorded by the Health Department in the past two weeks.\nA total of 309 confirmed cases and 524 suspected cases of dengue have been reported in the district this year till Monday. According to the Health Department, cases are mostly being reported from the areas on Chandigarh Road in Ludhiana. These include 33-foot Road, GTB Nagar, Mundian Kalan, Guru Nanak Nagar, GK Estate, Jamalpur, Sectors 32 and 39. There are chances that the number of dengue cases could be higher than official reports, say residents.\nThe department had recorded 31 confirmed dengue cases till September 22 and 115 cases till October 10 in these places. Apart from these cases, as many as 10 confirmed cases of chikungunya, which is also spread by bite of infected aedes mosquitoes, have been reported here this year.\nHealth team finds mosquito larvae in 438 containers\nHealth Inspector Manpreet Singh ..."
},
{
title : "Alarm bells ringing:194 dengue cases in 2 weeks in district",
url : "http://www.tribuneindia.com/news/ludhiana/alarm-bells-ringing-194-dengue-cases-in-2-weeks-in-district/486718.html",
source : "The Tribune",
date : "25.10.2017",
desc : "Tribune News Service\nLudhiana, October 24\nThe number of dengue cases is rapidly increasing in the district as 194 confirmed cases have been recorded by the Health Department in the past two weeks.\nA total of 309 confirmed cases and 524 suspected cases of dengue have been reported in the district this year till Monday. According to the Health Department, cases are mostly being reported from the areas on Chandigarh Road in Ludhiana. These include 33-foot Road, GTB Nagar, Mundian Kalan, Guru Nanak Nagar, GK Estate, Jamalpur, Sectors 32 and 39. There are chances that the number of dengue cases could be higher than official reports, say residents.\nThe department had recorded 31 confirmed dengue cases till September 22 and 115 cases till October 10 in these places. Apart from these cases, as many as 10 confirmed cases of chikungunya, which is also spread by bite of infected aedes mosquitoes, have been reported here this year.\nHealth team finds mosquito larvae in 438 containers\nHealth Inspector Manpreet Singh ..."
},
{
title : "650 new cases of dengue, 48 of chikungunya",
url : "http://www.thehindu.com/news/cities/Delhi/650-new-cases-of-dengue-48-of-chikungunya/article19908528.ece",
source : "Hindu: Cities",
date : "24.10.2017",
desc : "More than 1,000 dengue cases reported so far this month"
},
'' // Last item -- needed because previous item ends with a comma
]`
as you can see the sample data is not valid JSON, i tried the below function, however ended up with unnecessary space in the keys, which is also a problem.
`
//Step 1
function extractjson(strarg){
var found = [], // an array to collect the strings that are found
rxp = /{([^}]+)}/g,
curMatch;
var parsed=[];
// step 2: regex to add quotes
var objKeysRegex = /({|,)(?:\s*)(?:')?([A-Za-z_$\.][A-Za-z0-9_ \-\.$]*)(?:')?(?:\s*):/g;
while( curMatch = rxp.exec( strarg ) ) {
found.push( curMatch[0].replace(objKeysRegex, "$1\"$2\":") );
}
//step 3- parse the found data
for(i=0;i<found.length;i++){
try {
json = JSON.parse(found[i]);
} catch (exception) {
json = null;
}
if (json) {
//the json is ok
parsed.push(JSON.parse(found[i]));
}else{
console.log("badjson");
//the json is not ok
}
}
console.log("input length =", found.length, "output length=", parsed.length);
return parsed;
}
}
`
Here's a fairly naive attempt at parsing...it makes some assumptions about the format of the data (for example it looks for the _nr_ prefix on variable names). I'd recommend splitting the string up into its various var declarations, and then cleaning up each section of data between them before evaluating using JSON.parse.
let parseJSON = (text) => {
let quoteKeysAndParse = (text) => {
//Quote keys in objects
let quoted = text.replace(/([\{\[,]\s*)(['"])?([a-zA-Z0-9_]+)(['"])?\s*:/g, '$1"$3": ');
//Remove the "last item" text
quoted = quoted.replace(/,\s+'' \/\/ Last item[^\]^}]+([\]\}])/g, '$1');
//Remove improperly escaping of apostrophes
quoted = quoted.replace(/([^\\])\\'/g, '$1\'');
//Parse the JSON
return JSON.parse(quoted);
}
//Find var declarations
let declarations = text.match(/var\s+_nr_[^\s]+\s+=\s+/ig), obj = {}, key = null, prevKey = null;
text = ['',text];
//For each variable...
for(let declaration of declarations){
key = declaration.match(/_nr_[^\s]+/)[0];
let currentText = text[1].split(declaration);
text = currentText;
if(prevKey){
//Parse the prior split section
obj[prevKey] = quoteKeysAndParse(text[0]);
}
prevKey = key;
}
//Make sure we process the last section
if(prevKey){
obj[prevKey] = quoteKeysAndParse(text[1]);
}
return obj;
}
fetch('https://cors-anywhere.herokuapp.com/newsrack.in/stories/servelots/iihs_feeds/16.json')
.then(response => response.text())
.then(parseJSON)
.then(data => {
for(let item of data._nr_stories){
let div = document.createElement('div');
div.innerHTML = `<h3>${item.date} - ${item.title} (${item.source})</h3><p>${item.desc}</p>`;
document.body.append(div)
}
});
Here's a working short solution
// ----------------------- DATA -----------------------
let code = `
var _nr_metadata = {
site_base_url : "http://newsrack.in",
issue_name : "iihs_feeds",
category_name : "Chikungunya",
listing_url : "/stories/servelots/iihs_feeds/16"
}
var _nr_stories = [
{
title : "Alarm bells ringing:194 dengue cases in 2 weeks in district",
url : "http://www.tribuneindia.com/news/ludhiana/alarm-bells-ringing-194-dengue-cases-in-2-weeks-in-district/486718.html",
source : "The Tribune",
date : "25.10.2017",
desc : "Tribune News Service\nLudhiana, October 24\nThe number of dengue cases is rapidly increasing in the district as 194 confirmed cases have been recorded by the Health Department in the past two weeks.\nA total of 309 confirmed cases and 524 suspected cases of dengue have been reported in the district this year till Monday. According to the Health Department, cases are mostly being reported from the areas on Chandigarh Road in Ludhiana. These include 33-foot Road, GTB Nagar, Mundian Kalan, Guru Nanak Nagar, GK Estate, Jamalpur, Sectors 32 and 39. There are chances that the number of dengue cases could be higher than official reports, say residents.\nThe department had recorded 31 confirmed dengue cases till September 22 and 115 cases till October 10 in these places. Apart from these cases, as many as 10 confirmed cases of chikungunya, which is also spread by bite of infected aedes mosquitoes, have been reported here this year.\nHealth team finds mosquito larvae in 438 containers\nHealth Inspector Manpreet Singh ..."
},
{
title : "650 new cases of dengue, 48 of chikungunya",
url : "http://www.thehindu.com/news/cities/Delhi/650-new-cases-of-dengue-48-of-chikungunya/article19908528.ece",
source : "Hindu: Cities",
date : "24.10.2017",
desc : "More than 1,000 dengue cases reported so far this month"
},
]
`
// --------------------- / DATA ------------------------
// --------------------- TREATMENT ------------------------
// Add '"' around the property names
code = code.replace(/\n +([a-z_]+) +:/g, '"$1" :').replace(/[\n\r]/g,'');
// To avoid unecessary ',' in "}, ]"
code = code.replace(/\},[ ]*\]/g,'}]');
// Split by var (keeping var name)
code = code.split(/ var(?=[a-z_ ]+= [\[\{])/);
// The result to feed
let result = {} ;
// Treat each var
code.forEach( d => {
d = d.trim();
if (!d) { return }
// Separate var name and var value
// Faster?
let index = d.indexOf('=');
let var_name = d.substr(0, index).trim();
let var_value = d.substr(index+1, d.length).trim();
// Parse the value
try
{
result[var_name] = JSON.parse(var_value);
}
catch(error)
{
console.error(error);
}
})
console.log(result);
Kinda stuck on a problem so i got a controller looking like:
'use strict';
angular.module('Movie.services', []).service('Movie', ['$q', '$http', function($q, $http) {
/* global config*/
var API_URL = '';
var API_KEY = 'xxx';
var movieService = {
findCast : function( id ) {
var id = id; // get person id
var cast = [];
var promise = $http.get(API_URL + id, {
params: {
api_key: API_KEY
}}).then(function(result) {
angular.forEach(result, function(item) {
cast.push(item);
console.log(item);
});
return cast;
});
return promise;
},
getMovies : function(){
},
}
return movieService;
}]);
and it returns the whole object, fine.
Now i'm stuck on the part to parse is so in my main.js i got:
Movie.findCast(person_id).then(function(result){
$scope.getCast = result;
console.log($scope.getCast);
});
in my HTML i can do {{ getCast }} and i will get the whole JSON:
[{"adult":false,"also_known_as":[],"biography":"Seth Rogen (born April 15, 1982) is a Canadian actor, comedian, voice artist, screenwriter, and film producer. Rogen began his career doing stand-up comedy for four years during his teens, coming in second place in the Vancouver Amateur Comedy Contest in 1998. While still living in his native Vancouver, he landed a supporting role in Freaks and Geeks. Shortly after Rogen moved to Los Angeles for his role, Freaks and Geeks was canceled after one season due to poor ratings. He then got a part on the equally short-lived Undeclared, which also hired him as a staff writer.\nAfter landing a job as a staff writer on the final season of Da Ali G Show, for which Rogen and the other writers received an Emmy nomination, he was guided by film producer Judd Apatow toward a film career. Rogen was cast in a major supporting role and credited as a co-producer in Apatow's directorial debut, The 40-Year-Old Virgin. \n\nAfter receiving critical praise for that performance, Universal Pictures agreed to cast him as the lead in Apatow's next directorial feature, Knocked Up.\n\nRogen has appeared in the films Donnie Darko, You, Me and Dupree, Zack and Miri Make a Porno, Observe and Report, and The Green Hornet, and also in the Apatow-produced comedies The 40-Year-Old Virgin, Knocked Up, Superbad, Pineapple Express, and Funny People. He and his comedy partner Evan Goldberg co-wrote the comedy films Superbad and Pineapple Express, for which he originally intended to headline while in high school. Rogen has provided voice talents in the animated films Horton Hears a Who!, Kung Fu Panda, and Monsters vs. Aliens. He also supports Crowdrise, a charitable networking site.","birthday":"1982-04-15","deathday":"","homepage":"http://www.seth-rogen.com/","id":19274,"imdb_id":"nm0736622","name":"Seth Rogen","place_of_birth":"Vancouver, British Columbia, Canada","popularity":14.8509727429298,"profile_path":"/3U9s4dvXQuk1l3ZT3MqwqpmeRqI.jpg"},200,null,{"method":"GET","transformRequest":[null],"transformResponse":[null],"params":{"api_key":"0df011bca7e5171f5bea292e818ace29"},"url":"http://api.themoviedb.org/3/person/19274","headers":{"Accept":"application/json, text/plain, */*"}},"OK"]
but as soon as i try to do {{ getCast.biography }} it will give me undefined.
How can i parse the data?
That's because it's not getCast.biography but getCast[0].biography.
How would i parse the json data below to out put as
Staring: Will Smith, Bridget Moynahan, Bruce GreenWood
{"query":{"\n| starring = [[Will Smith]]<br />[[Bridget Moynahan]]<br />[[Bruce Greenwood]]<br />[[James Cromwell]]<br />[[Chi McBride]]<br />[[Alan Tudyk]]}}
This was taken from here
{
"query": {
"normalized": [
{
"from": "I,_Robot_(film)",
"to": "I, Robot (film)"
}
],
"pages": {
"564947": {
"pageid": 564947,
"ns": 0,
"title": "I, Robot (film)",
"revisions": [
{
"contentformat": "text/x-wiki",
"contentmodel": "wikitext",
"*": "{{Other uses|I, Robot (disambiguation)}}\n{{Infobox film\n| name = I, Robot\n| image = Movie poster i robot.jpg\n| caption = Theatrical release poster\n| director = [[Alex Proyas]]\n| producer = [[Laurence Mark]]<br />[[John Davis (producer)|John Davis]]<br />Topher Dow<br />Wyck Godfrey\n| screenplay = [[Jeff Vintar]]<br />[[Akiva Goldsman]]\n| story = Jeff Vintar\n| based on = {{Based on|premise suggested by ''[[I, Robot]]''|[[Isaac Asimov]]}}\n| starring = [[Will Smith]]<br />[[Bridget Moynahan]]<br />[[Bruce Greenwood]]<br />[[James Cromwell]]<br />[[Chi McBride]]<br />[[Alan Tudyk]]\n| music = [[Marco Beltrami]]\n| cinematography = Simon Duggan\n| editing = Richard Learoyd<br />Armen Minasian<br />[[William Hoy]]\n| studio = [[Davis Entertainment]]<br />[[Laurence Mark Productions]]<br />[[Overbrook Entertainment|Overbrook Films]]<br/>[[Rainmaker Digital Effects]] (Provided)\n| distributor = [[20th Century Fox]]\n| released = {{Film date|2004|7|15|international|2004|7|16|United States}}\n| runtime = 115 minutes\n| country = United States\n| language = English\n| budget = $120 million\n| gross = $347,234,916\n}}\n'''''I, Robot''''' is a 2004 American [[dystopia]]n [[science fiction film|science fiction]] [[action film]] directed by [[Alex Proyas]]. The screenplay was written by [[Jeff Vintar]] and [[Akiva Goldsman]], and is inspired by (\"suggested by\", according to the end credits) [[Isaac Asimov]]'s short-story collection [[I, Robot|of the same name]]. [[Will Smith]] stars in the lead role of the film as Detective Del Spooner. The supporting cast includes [[Bridget Moynahan]], [[Bruce Greenwood]], [[James Cromwell]], [[Chi McBride]], [[Alan Tudyk]], and [[Shia LaBeouf]]. \n\n''I, Robot'' was released in [[North America]] on July 16, 2004, in [[Australia]] on July 22, 2004, in the [[United Kingdom]] on August 6, 2004 and in other countries between July 2004 to October 2004. Produced with a budget of [[United States dollar|USD]] $120 million, the film grossed $144 million domestically and $202 million in foreign markets for a worldwide total of $347 million. The movie received favorable reviews, with critics praising the writing, visual effects, and acting; but other critics were mixed with the focus on the plot. It was nominated for the 2004 [[Academy Award for Best Visual Effects]], but lost to ''[[Spider-Man 2]]''."
}
]
}
}
}
}
With the url being:
http://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&format=json&titles=I,Robot(film)&rvsection=0
Your help would be greatly appreciated.
Thank You,
use:
var Jsonstring = {title: "Movie", actors: [ 'actor1','actor2']};
var movie = $.parseJSON(Jsonstring);
alert(movie.title); //will alert Movie
alert(movie.actors[0]) // will alert actor1
this function will convert your json string to javascript object.
http://api.jquery.com/jquery.parsejson/
You can parse it with RegExp:
var str = obj.query.pages[564947].revisions[0]['*'],
matches = str.match(/\|\s+(starring)\s+=\s+(.+)\n/),
result = matches[1] + ': ' + matches[2].replace(/<br\s+\/>/ig, ', ').replace(/[\[\]]/ig, '');
There will be starring: Will Smith, Bridget Moynahan, Bruce Greenwood, James Cromwell, Chi McBride, Alan Tudyk in the result variable.
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.
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"]];