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.
Related
I've created this function.
I think I'm missing something very obvious but when I call this function, it keeps running where instead I only want "tweeter" to run once when it is called. Instead, it seems to be looping every minute or so and then posting again.
Any help would be greatly appreciated.
function tweeter() {
//Fetch API Documentation
fetch('[MY API URL]').then(response=> response.json()).then(function (data) {
//Function to create array
//Define Array
var array =[];
let tweetText ='';
//Loop data.data
for (var i = 0; i < data.data.length; i++) {
var minutes = (data.data[i][1]);
//Push values to Array
array.push(minutes);
}
//SUM of array
var sum = array.reduce(function(a, b){
return a + b;
}, 0);
//Return rounded value of average of Cork City sensors.
let sensorAverage = (Math.round(sum / data.data.length));
/* Messaging based on the SensorAverage returned.
Based on EU PM2.5 AQI
0-10:
10-20:
20-25:
50-75:
75-800:
800:
*/
if(sensorAverage <= 10){
tweetText = " \n\n0-10 = Good. \n\nThe air quality is good in Cork City at the moment. \nEnjoy your usual outdoor activities worry-free. " ;
} else if((sensorAverage >=10.1) && (sensorAverage <=19.9)){
tweetText = "\n\n10-20 = Fair. \n\nThe air quality is fair in Cork City at the moment.. \nEnjoy your usual outdoor activities.";
} else if((sensorAverage >=20) && (sensorAverage <=24.9)){
tweetText = "\n\n20-25 = Moderate. \n\nThe air quality is moderate in Cork City at the moment. \nEnjoy your usual outdoor activities. Sensitive groups should consider reducing intense outdoor activities, if you experience symptoms.";
} else if((sensorAverage >=25) && (sensorAverage <=49.9)){
tweetText = "\n\n20-25 = Moderate. \n\nThe air quality is moderate in Cork City at the moment. \nEnjoy your usual outdoor activities. Sensitive groups should consider reducing intense outdoor activities, if you experience symptoms.";
}else if((sensorAverage >=50) && (sensorAverage <=74.9)){
tweetText = "\n\n50-75 = Very Poor. \n\nThe air quality is very poor in Cork City at the moment. \nConsider reducing intense activities outdoors. Sensitive groups should reduce physical activities.";
} else if((sensorAverage >=75) && (sensorAverage <=)){
tweetText = "\n\n75-800 = Extremely Poor. \n\nThe air quality is very poor in Cork City at the moment. \nReduce physical activities outdoors. Sensitive groups should avoid physical activities outdoors.";
} else if (sensorAverage > 800){
tweetText = "\n\n>800 = Catastrophicly Poor. \n\nThe air quality is catastrophic in Cork City at the moment. \nAvoid outdoor activities.";
}
var tweet = "The average reading across Cork City is currently " + sensorAverage + "*. " + tweetText + "\n\n*Based on EU PM2.5 AQI. \n\n#CorkAirQuality";
T.post('statuses/update', { status: tweet }, tweeter);
});
}
I am thinking it's this line :-
T.post('statuses/update', { status: tweet }, tweeter);
This can be possible if you're passing tweeter as a callback function to your T.post code (I am not aware of how you implemented it).
So everytime the POST request completes, the tweeter callback might be getting triggered.
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);
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.
So, I'm new to programming, but I'm trying to learn JavaScript. Currently I'm working on a project where I'm trying to parse a large text file (the 154 sonnets of Shakespeare found here) into an object array, in the following data structure:
var obj = {
property 1: [ 'value 1',
'value 2',
],
property 2: [ 'value 1',
'value 2',
],
etc., where roman numerals represent object properties and each line of the sonnet represents a value in each property's array.
I must use regular expressions to parse through the text file. So far I've been searching for the correct regexp to demarcate the text, but I don't know if I'm going about this the right way. Ultimately I want to create a drop down menu where each value in the list is a sonnet.
Edit: I'm actually now taking the source text from this url: http://pizzaboys.biz/xxx/sonnets.php
and doing the same thing as above, but instead of doing a $get I've put the text into a variable...
I've tried this:
$(document).ready(function(){
var data = new SonnetizerArray();
});
function SonnetizerArray(){
this.data = [];
var rawText = "text from above link"
var rx = /^\\n[CDILVX]/$\\n/g;
var array_of_sonnets = rawText.exec(rx);
for (var i = 0; i < array_of_sonnets.length; i ++){
var s = $.split(array_of_sonnets[i]);
if (s.length > 0) this.data.push(s);
}
}
Description
This regex will parse the text into a roman numeral and body. The body can then be split on the new line \n.
^\s+\b([CDMLXVI]{1,12})\b(?:\r|\n|$).*?(?:^.*?)(^.*?)(?=^\s+\b([MLXVI]{1,12})\b(?:\r|\n|$)|\Z)
Capture Groups
Group 0 get the entire matching section
gets the roman numeral
gets the body of the section, not including the roman numeral
Javascript Code Example:
Sample text pulled from your link
VII
Lo! in the orient when the gracious light
Lifts up his burning head, each under eye
Doth homage to his new-appearing sight,
VIII
Music to hear, why hear'st thou music sadly?
Sweets with sweets war not, joy delights in joy:
Why lov'st thou that which thou receiv'st not gladly,
Or else receiv'st with pleasure thine annoy?
IX
Is it for fear to wet a widow's eye,
That thou consum'st thy self in single life?
Ah! if thou issueless shalt hap to die,
The world will wail thee like a makeless wife;
Example code
<script type="text/javascript">
var re = /^\s+\b([MLXVI]{1,12})\b(?:\r|\n|$).*?(?:^.*?)(^.*?)(?=^\s+\b([MLXVI]{1,12})\b(?:\r|\n|$)|\Z)/;
var sourcestring = "source string to match with pattern";
var results = [];
var i = 0;
for (var matches = re.exec(sourcestring); matches != null; matches = re.exec(sourcestring)) {
results[i] = matches;
for (var j=0; j<matches.length; j++) {
alert("results["+i+"]["+j+"] = " + results[i][j]);
}
i++;
}
</script>
Sample output
$matches Array:
(
[0] => Array
(
[0] => VII
Lo! in the orient when the gracious light
Lifts up his burning head, each under eye
Doth homage to his new-appearing sight,
[1] =>
VIII
Music to hear, why hear'st thou music sadly?
Sweets with sweets war not, joy delights in joy:
Why lov'st thou that which thou receiv'st not gladly,
Or else receiv'st with pleasure thine annoy?
[2] =>
IX
Is it for fear to wet a widow's eye,
That thou consum'st thy self in single life?
Ah! if thou issueless shalt hap to die,
The world will wail thee like a makeless wife;
)
[1] => Array
(
[0] => VII
[1] => VIII
[2] => IX
)
[2] => Array
(
[0] =>
Lo! in the orient when the gracious light
Lifts up his burning head, each under eye
Doth homage to his new-appearing sight,
[1] =>
Music to hear, why hear'st thou music sadly?
Sweets with sweets war not, joy delights in joy:
Why lov'st thou that which thou receiv'st not gladly,
Or else receiv'st with pleasure thine annoy?
[2] =>
Is it for fear to wet a widow's eye,
That thou consum'st thy self in single life?
Ah! if thou issueless shalt hap to die,
The world will wail thee like a makeless wife;
)
[3] => Array
(
[0] => VIII
[1] => IX
[2] =>
)
)
Roman numeral validation
The above expression only tests the roman numeral string is composed of roman numeral characters, it doesn't actually validate the number is valid. If you need to validate the roman numeral is correctly formatted too, then you could use this expression.
^\s+\b(M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3}))\b(?:\r|\n|$).*?(?:^.*?)(^.*?)(?=^\s+\b([MLXVI]{1,12})\b(?:\r|\n|$)|\Z)
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.