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.
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.
I have a very long array of names like this:
namelist = [ "Andrew Alexander Brown", "Charlie Christopher Drake", "Edward Elsevier Furlong", "Gareth Gates Harper", "Indiana Chewbacca Jones", "Kevin M Lamarr", "Michael Randy Newman", "Oliver Terry Pratchett", "Queen Liz Regina", "Stuart Townsend", "Umar Vespa", "Woodford X Xanadu", "Yanick Zebra" ];
I would like to extract the names from the list into strings with each name separated by a pipe character (|). Each new string should be smaller than 48 characters, for instance the output should be like this (but less than or equal to 48 characters):
Andrew Alexander Brown|Charlie Christopher Drake|Edward Elsevier Furlong
Gareth Gates Harper|Indiana Chewbacca Jones|Kevin M Lamarr
Michael Randy Newman|Oliver Terry Pratchett|Queen Liz Regina
Stuart Townsend|Umar Vespa|Woodford X Xanadu|Yanick Zebra
I would like the number of new strings to be as small as possible, probably without maintaining the order of the strings in the array - but I am at a loss at how to do this in javascript.
I know I could do something like loop through the namelist and add the next name onto a temporary string. Check the length of this temporary string and output it if it exceeds 48 characters. Keep going around the loop until we have run out of names but this doesn't seem very efficient. For instance if a short name is followed by an extremely long name then characters (which could be filled by another smaller name in the temporary string) will be wasted.
Any pointers at how best to achieve this?
This is what is knows as The Bin Packing Problem
Solutions will depend on your definition of efficient, more efficient bin packing tends to take longer to compute. But less efficient bin packing tends to take much less computational resources (could be deemed more efficient in terms of computational resources).
Here is my solution using ECMA5 specifications, it sacrifices computational resources in favour of more efficient bin packing.
I have chosen to leave the powerSet function a general purpose one, that means it can be reused for other purposes. As #Bergi has highlighted, you may get better efficiency with respect to computational resources if you created a custom function which incorporates the first filter from joinStringsMaxCharacters
Javascript
General Power Set function
function powerSet(array) {
var lastElement,
sets;
if (!array.length) {
sets = [[]];
} else {
lastElement = array.pop();
sets = powerSet(array).reduce(function (previous, element) {
previous.push(element);
element = element.slice();
element.push(lastElement);
previous.push(element);
return previous;
}, []);
}
return sets;
}
Helper functions
function isString(element) {
return typeof element === 'string';
}
function isNotUsed(element) {
return this.every(function (u) {
return u.indexOf(element) === -1;
});
}
function sumLength(s, el) {
return s + el.length;
}
Packing bins with joined strings
function joinStringsMaxCharacters(arrayOfStrings, numberOfCharacters, separator) {
if (!Array.isArray(arrayOfStrings) || !arrayOfStrings.every(isString)) {
throw new TypeError('arrayOfStrings is not an array of strings!');
}
numberOfCharacters = numberOfCharacters >>> 0;
if (!separator || !isString(separator)) {
separator = '|';
}
var arrayLength = arrayOfStrings.length;
return powerSet(arrayOfStrings).filter(function (set) {
return set.length && (set.length === 1 || set.reduce(sumLength, set.length - 1) <= numberOfCharacters);
}).sort(function (a, b) {
return b.reduce(sumLength, b.length) - a.reduce(sumLength, a.length) || b.length - a.length;
}).reduce(function (used, cur) {
if (used.reduce(sumLength, 0) < arrayLength && cur.every(isNotUsed, used)) {
used.push(cur);
}
return used;
}, []).map(function (bin) {
return bin.join(separator);
});
}
Array of strings to be packed into bins
var nameList = [
"Andrew Alexander Brown",
"Charlie Christopher Drake",
"Edward Elsevier Furlong",
"Gareth Gates Harper",
"Indiana Chewbacca Jones",
"Kevin M Lamarr",
"Michael Randy Newman",
"Oliver Terry Pratchett",
"Queen Liz Regina",
"Stuart Townsend",
"Umar Vespa",
"Woodford X Xanadu",
"Yanick Zebra"];
Pack the bins and display the content of each bin
joinStringsMaxCharacters(nameList, 48).forEach(function (bin) {
console.log(bin);
});
Output
Kevin M Lamarr|Stuart Townsend|Woodford X Xanadu
Michael Randy Newman|Queen Liz Regina|Umar Vespa
Charlie Christopher Drake|Oliver Terry Pratchett
Edward Elsevier Furlong|Indiana Chewbacca Jones
Andrew Alexander Brown|Gareth Gates Harper
Yanick Zebra
On jsFiddle
var namelist= ["Andrew Alexander Brown", "Charlie Christopher Drake", "Edward Elsevier Furlong", "Gareth Gates Harper", "Indiana Chewbacca Jones", "Kevin M Lamarr", "Michael Randy Newman", "Oliver Terry Pratchett", "Queen Liz Regina", "Stuart Townsend", "Umar Vespa", "Woodford X Xanadu", "Yanick Zebra"];
var c48= [], next, temp= '', i= 0, L= namelist.length;
while(i<L){
next= namelist[i++];
if((temp+next).length<= 47) temp=temp? temp+'|'+next: next;
else{
c48.push(temp);
temp= next;
}
}
if(next)c48.push(next);
c48.join('\n')
/* returned value: (String)
Andrew Alexander Brown|Charlie Christopher Drake
Edward Elsevier Furlong|Gareth Gates Harper
Indiana Chewbacca Jones|Kevin M Lamarr
Michael Randy Newman|Oliver Terry Pratchett
Queen Liz Regina|Stuart Townsend|Umar Vespa
Yanick Zebra
*/
What's a good JavaScript library for searching a given string for a large list of names.
For example, given a list of 1000 politicians names find every instance in a string and wrap it in a span.
Priorities are performance with a growing list of names, and accuracy in determining difference between eg, "Tony Blair", "Tony Blair III".
For example, this:
["Tony Blair", "Margaret Thatcher", "Tony Blairite", "Tony Blair III", etc...]
"The best PM after Tony Blair was Margaret Thatcher."
Becomes:
"The best PM after <span class="mp">Tony Blair</span> was <span class="mp">Margaret Thatcher</span>."
var names = ['foo','bar'];
var content = "this foo is bar foobar foo ";
for (var c=0,l=names.length;c<l;c++) {
var r = new RegExp("\\b("+names[c]+")\\b","gi");
content = content.replace(r,'<span class="mp">$1</span>');
}
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.