Nested JSON Dataframe - json

I am trying to create a dataframe out of nested JSON files and am running into issues. So far, I've tried using tidyjson to stack the different columns like author, source, etc. However, when I get to "readers" (see the second JSON record), instead of column headers proceeding the ":" there is a unique id. I can't figure out how to get around that and create a dataframe. Here is the code I have so far:
art_df <- artJSON %>%
as.tbl_json %>%
gather_array %>%
enter_object("articles") %>% gather_array %>% # stack the articles
enter_object("author") %>% gather_array %>% # stack the authors
spread_values(articles.author = jstring("author")) %>% # extract item name and price
spread_values(articles.date = jstring("date")) %>%
) %>%
And the JSON file is structured like:
"articles" : {
"-2145189873" : {
"author" : "",
"date" : "",
"partialRecord" : true,
"source" : "reuters",
"text" : "",
"title" : "U.S. government loses to Russia's disinformation campaign: advisers | Reuters",
"url" : "reuters.com/article/us-usa-russia-disinformation-analysis-idUSKBN1492PA"
},
"-2143576379" : {
"author" : [ "", "", "CNN" ],
"date" : "Updated 8:21 AM ET, Mon June 19, 2017",
"readers" : {
"112851530401572877131" : true,
"115171523766335420644" : true
},
"source" : "cnn",
"text" : "Story highlightsThe higher the pressure, the more defiant the President becomesTrump continues to call the Russia probe a 'witch hunt' Washington (CNN)America is edging ever closer to a new long, national nightmare, given President Donald Trump's explosive response to signs that special counsel Robert Mueller is approaching the epicenter of White House power.The investigation has taken a serious turn in recent days, raising the clear possibility that whether Mueller finds wrongdoing or not, a period of political stress and upheaval is inevitable. Trump appears willing to test the bounds of convention and his own powers against a legal and political establishment that he believes is conspiring against him. The higher the pressure, the more defiant the President becomes -- even if it puts him at odds with his legal team.Trump has decided that \"this is a political fight and he's going to fight it,\" a White House official told CNN's Jeff Zeleny.But the sense of chaos around the White House is deepening. The President again called the Russia probe a \"witch hunt\" over the weekend while a legal adviser tried to walk back Trump's admission Friday that he is under investigation.Read More\"The MAKE AMERICA GREAT AGAIN agenda is doing very well despite the distraction of the Witch Hunt,\" Trump tweeted on Sunday.var id = '//platform.twitter.com/widgets.js'.replace(/\\s+/g, '');!!document.getElementById(id) || (function makeEmbedScript(d, id) (document, id));The MAKE AMERICA GREAT AGAIN agenda is doing very well despite the distraction of the Witch Hunt. Many new jobs, high business enthusiasm,..— Donald J. Trump (#realDonaldTrump) June 18, 2017The political stakes rose significantly in recent days amid signs the probe on Russian election hacking could eventually expand to consider Trump's actions.The President and his allies have declared open season on Mueller and Deputy Attorney General Rod Rosenstein, who is overseeing the probe. \"You are witnessing the single greatest WITCH HUNT in American political history - led by some very bad and conflicted people! #MAGA.\" Trump said in a tweet last week that signified an attempt to undermine both men./* global CNN, Modernizr */'use strict';CNN.INJECTOR.executeFeature('video').then(function () {CNN.VideoPlayer.handleUnmutePlayer = function handleUnmutePlayer(containerId, dataObj) {'use strict';var playerInstance,playerPropertyObj,rememberTime,unmuteCTA,unmuteIdSelector = 'unmute_' + containerId,isPlayerMute;dataObj = dataObj || {};if (CNN.VideoPlayer.getLibraryName(containerId) === 'fave') else isPlayerMute = (typeof dataObj.muted === 'boolean') ? dataObj.muted : false;if (CNN.VideoPlayer.playerProperties && CNN.VideoPlayer.playerProperties[containerId]) if (playerPropertyObj.mute && playerPropertyObj.contentPlayed) };CNN.VideoPlayer.showFlashSlate = function showFlashSlate(container) ;CNN.autoPlayVideoExist = (CNN.autoPlayVideoExist === true) ? true : false;var configObj = ,autoStartVideo = false,callbackObj,containerEl,currentVideoCollection = [],currentVideoCollectionId = '',isLivePlayer = false,moveToNextTimeout,mutePlayerEnabled = false,nextVideoId = '',nextVideoUrl = '',turnOnFlashMessaging = false,videoPinner,videoEndSlateImpl;if (CNN.autoPlayVideoExist === false) configObj.autostart = autoStartVideo;CNN.VideoPlayer.setPlayerProperties(configObj.markupId, autoStartVideo, isLivePlayer, mutePlayerEnabled);CNN.VideoPlayer.setFirstVideoInCollection(currentVideoCollection, configObj.markupId);videoEndSlateImpl = new CNN.VideoEndSlate('body-text_15');/*** Finds the next video ID and URL in the current collection, if available.* #param currentVideoId The video that is currently playing* #param containerId The parent container Id of the video element*/function findNextVideo(currentVideoId) findNextVideo('tv/2017/06/18/reliable-sources-journalists-trump-twitter-habit.cnn');/*** Navigates to the video leaf page of the next video in the current collection, if available.* #param currentVideoId The video that is currently playing* #param containerId The parent container Id of the video element*/function navigateToNextVideo(currentVideoId, containerId) callbackObj = ;if (typeof configObj.context !== 'string' || configObj.context.length 0) CNN.autoPlayVideoExist = (CNN.autoPlayVideoExist === true) ? true : false;CNN.VideoPlayer.getLibrary(configObj, callbackObj, isLivePlayer);});/* videodemanddust is a default feature of the injector */CNN.INJECTOR.scriptComplete('videodemanddust');JUST WATCHEDWhy journalists like Trump's Twitter habitReplayMore Videos ...MUST WATCHWhy journalists like Trump's Twitter habit 05:59The tweet sparked speculation that Trump may pull a nuclear option by firing Mueller and Rosenstein, a move senior aides have fervently advised against -- given that it could provoke a constitutional crisis.\"It looks like we have got a simmering tea kettle here, and the President seems to be testing the waters about whether he ought to go ahead and fire Robert Mueller,\" said Richard Ben-Veniste, a former Watergate prosecutor who is now a CNN legal analyst.\"You don't mess with the criminal justice system in this way ... the President is on very tenuous ground here,\" Ben-Veniste told CNN's Don Lemon Friday.Cuba to Trump: US in no 'condition to lecture us' on human rightsThe scorched-earth approach may have grave political consequences.Trump and his aides may well end up in the clear, but months of recriminations ahead will further polarize the capital and cast a shadow over his administration, which is already struggling for traction after a tumultuous first five months.If Mueller decides there is a case to answer for either the President or his aides in the issue of alleged collusion with Russia or over a potential cover-up, the political uproar will be incalculable.At best, it could further complicate Trump's efforts to pass a meaningful legislative agenda and ultimately his hopes of a successful presidency.At worst, it could force the nation to confront a third debate on whether to remove an elected President in just 45 years. The lessons of history suggest such traumas raise questions of political legitimacy and constitutional process that have the potential to sour life in Washington for years in the future./* global CNN, Modernizr */'use strict';CNN.INJECTOR.executeFeature('video').then(function () {CNN.VideoPlayer.handleUnmutePlayer = function handleUnmutePlayer(containerId, dataObj) {'use strict';var playerInstance,playerPropertyObj,rememberTime,unmuteCTA,unmuteIdSelector = 'unmute_' + containerId,isPlayerMute;dataObj = dataObj || {};if (CNN.VideoPlayer.getLibraryName(containerId) === 'fave') else isPlayerMute = (typeof dataObj.muted === 'boolean') ? dataObj.muted : false;if (CNN.VideoPlayer.playerProperties && CNN.VideoPlayer.playerProperties[containerId]) if (playerPropertyObj.mute && playerPropertyObj.contentPlayed) };CNN.VideoPlayer.showFlashSlate = function showFlashSlate(container) ;CNN.autoPlayVideoExist = (CNN.autoPlayVideoExist === true) ? true : false;var configObj = ,autoStartVideo = false,callbackObj,containerEl,currentVideoCollection = [],currentVideoCollectionId = '',isLivePlayer = false,moveToNextTimeout,mutePlayerEnabled = false,nextVideoId = '',nextVideoUrl = '',turnOnFlashMessaging = false,videoPinner,videoEndSlateImpl;if (CNN.autoPlayVideoExist === false) configObj.autostart = autoStartVideo;CNN.VideoPlayer.setPlayerProperties(configObj.markupId, autoStartVideo, isLivePlayer, mutePlayerEnabled);CNN.VideoPlayer.setFirstVideoInCollection(currentVideoCollection, configObj.markupId);videoEndSlateImpl = new CNN.VideoEndSlate('body-text_25');/*** Finds the next video ID and URL in the current collection, if available.* #param currentVideoId The video that is currently playing* #param containerId The parent container Id of the video element*/function findNextVideo(currentVideoId) findNextVideo('politics/2017/06/18/jay-sekulow-trump-obstruction-of-justice-sotu.cnn');/*** Navigates to the video leaf page of the next video in the current collection, if available.* #param currentVideoId The video that is currently playing* #param containerId The parent container Id of the video element*/function navigateToNextVideo(currentVideoId, containerId) callbackObj = ;if (typeof configObj.context !== 'string' || configObj.context.length 0) CNN.autoPlayVideoExist = (CNN.autoPlayVideoExist === true) ? true : false;CNN.VideoPlayer.getLibrary(configObj, callbackObj, isLivePlayer);});/* videodemanddust is a default feature of the injector */CNN.INJECTOR.scriptComplete('videodemanddust');JUST WATCHEDSekulow: POTUS has power to fire FBI directorReplayMore Videos ...MUST WATCHSekulow: POTUS has power to fire FBI director 00:10Trump's in 'a political fight and he's going to fight it'Back in the present, the President's mood is fueling the sense of crisis.\"One thing we've learned I think from the testimony of multiple people now is the President's pretty fired up about this, OK?\" Republican Sen. Marco Rubio said on NBC's \"Meet the Press\" Sunday.\"He, from every pronouncement we have seen, feels very strongly that he did nothing wrong, and he wants people to say that, because he feels very strongly about it,\" Rubio said. \"I don't think that's a mystery. And he's expressing himself in that way.\"But the more frustrated that Trump gets, the more he often hurts himself politically. A case in point is the firing of Comey and Trump's subsequent admission that he had Russia on his mind when he dismissed the FBI director, an admission that could provide a rationale for an obstruction of justice probe.\"Trump has a compulsion to counter-attack and is very pugnacious. I don't think it serves him well,\" former House Speaker Newt Gingrich, a Trump supporter, on ABC's \"This Week,\" adding that the President was right to be infuriated by \"this whole Russia baloney.\"/* global CNN, Modernizr */'use strict';CNN.INJECTOR.executeFeature('video').then(function () {CNN.VideoPlayer.handleUnmutePlayer = function handleUnmutePlayer(containerId, dataObj) {'use strict';var playerInstance,playerPropertyObj,rememberTime,unmuteCTA,unmuteIdSelector = 'unmute_' + containerId,isPlayerMute;dataObj = dataObj || {};if (CNN.VideoPlayer.getLibraryName(containerId) === 'fave') else isPlayerMute = (typeof dataObj.muted === 'boolean') ? dataObj.muted : false;if (CNN.VideoPlayer.playerProperties && CNN.VideoPlayer.playerProperties[containerId]) if (playerPropertyObj.mute && playerPropertyObj.contentPlayed) };CNN.VideoPlayer.showFlashSlate = function showFlashSlate(container) ;CNN.autoPlayVideoExist = (CNN.autoPlayVideoExist === true) ? true : false;var configObj = ,autoStartVideo = false,callbackObj,containerEl,currentVideoCollection = [],currentVideoCollectionId = '',isLivePlayer = false,moveToNextTimeout,mutePlayerEnabled = false,nextVideoId = '',nextVideoUrl = '',turnOnFlashMessaging = false,videoPinner,videoEndSlateImpl;if (CNN.autoPlayVideoExist === false) configObj.autostart = autoStartVideo;CNN.VideoPlayer.setPlayerProperties(configObj.markupId, autoStartVideo, isLivePlayer, mutePlayerEnabled);CNN.VideoPlayer.setFirstVideoInCollection(currentVideoCollection, configObj.markupId);videoEndSlateImpl = new CNN.VideoEndSlate('body-text_34');/*** Finds the next video ID and URL in the current collection, if available.* #param currentVideoId The video that is currently playing* #param containerId The parent container Id of the video element*/function findNextVideo(currentVideoId) findNextVideo('politics/2017/06/18/sotu-rubio-trump-talked-russia-probe-in-private.cnn');/*** Navigates to the video leaf page of the next video in the current collection, if available.* #param currentVideoId The video that is currently playing* #param containerId The parent container Id of the video element*/function navigateToNextVideo(currentVideoId, containerId) callbackObj = ;if (typeof configObj.context !== 'string' || configObj.context.length 0) CNN.autoPlayVideoExist = (CNN.autoPlayVideoExist === true) ? true : false;CNN.VideoPlayer.getLibrary(configObj, callbackObj, isLivePlayer);});/* videodemanddust is a default feature of the injector */CNN.INJECTOR.scriptComplete('videodemanddust');JUST WATCHEDRubio: Trump talked Russia probe in privateReplayMore Videos ...MUST WATCHRubio: Trump talked Russia probe in private 01:05Legal team contradicts the clientIn another sign of the gravity of the situation, Trump's legal team blitzed Sunday talk shows to contradict the President's tweet Friday where he said he is already under investigation.\"The President is not a subject or target of an investigation. That tweet was in response to a Washington Post story that ran with five unnamed sources, without identifying the agencies they represented, saying that the special counsel had broadened out his investigation to include the president,\" said Jay Sekulow, a Trump legal adviser on CNN's \"State of the Union.\"Sekulow also opened a conflict between the President's political team and his legal one, hinting that the President's tweets should be discounted even though the White House said they are an authentic expression of his views.\"It was 141 characters. There's a limitation on Twitter, as we all know,\" Sekulow said.Then, in a subsequent interview on \"Fox News Sunday,\" Sekulow sowed further confusion by saying Trump was under investigation -- then denied he said anything of the sort.Special counsel moving forwardLaw enforcement sources have told CNN that the special counsel is gathering information and considering whether there is evidence to launch a full scale obstruction investigation. Mueller's investigators have asked for information and will talk to Director of National Intelligence Dan Coats and National Security Agency Director Adm. Mike Rogers, according to a source familiar with the matter. Investigators have also sought information from recently retired NSA Deputy Richard Ledgett, according to the source. Ledgett wrote a memo, according to the source, documenting a conversation in which the president allegedly urged Rogers to help get the FBI to lift the cloud of the Russia investigation.Any confirmation that Mueller has expanded the investigation to consider whether the President obstructed justice with the Comey firing would carry no guarantee of a guilty finding.But it would deal a political blow to the White House in the battle of perception, since the idea that Trump is not under investigation has been at the centerpiece of his administration's defense strategy./* global CNN, Modernizr */'use strict';CNN.INJECTOR.executeFeature('video').then(function () {CNN.VideoPlayer.handleUnmutePlayer = function handleUnmutePlayer(containerId, dataObj) {'use strict';var playerInstance,playerPropertyObj,rememberTime,unmuteCTA,unmuteIdSelector = 'unmute_' + containerId,isPlayerMute;dataObj = dataObj || {};if (CNN.VideoPlayer.getLibraryName(containerId) === 'fave') else isPlayerMute = (typeof dataObj.muted === 'boolean') ? dataObj.muted : false;if (CNN.VideoPlayer.playerProperties && CNN.VideoPlayer.playerProperties[containerId]) if (playerPropertyObj.mute && playerPropertyObj.contentPlayed) };CNN.VideoPlayer.showFlashSlate = function showFlashSlate(container) ;CNN.autoPlayVideoExist = (CNN.autoPlayVideoExist === true) ? true : false;var configObj = ,autoStartVideo = false,callbackObj,containerEl,currentVideoCollection = [],currentVideoCollectionId = '',isLivePlayer = false,moveToNextTimeout,mutePlayerEnabled = false,nextVideoId = '',nextVideoUrl = '',turnOnFlashMessaging = false,videoPinner,videoEndSlateImpl;if (CNN.autoPlayVideoExist === false) configObj.autostart = autoStartVideo;CNN.VideoPlayer.setPlayerProperties(configObj.markupId, autoStartVideo, isLivePlayer, mutePlayerEnabled);CNN.VideoPlayer.setFirstVideoInCollection(currentVideoCollection, configObj.markupId);videoEndSlateImpl = new CNN.VideoEndSlate('body-text_48');/*** Finds the next video ID and URL in the current collection, if available.* #param currentVideoId The video that is currently playing* #param containerId The parent container Id of the video element*/function findNextVideo(currentVideoId) findNextVideo('tv/2017/06/18/inside-politics-6-18-notebooks.cnn');/*** Navigates to the video leaf page of the next video in the current collection, if available.* #param currentVideoId The video that is currently playing* #param containerId The parent container Id of the video element*/function navigateToNextVideo(currentVideoId, containerId) callbackObj = ;if (typeof configObj.context !== 'string' || configObj.context.length 0) CNN.autoPlayVideoExist = (CNN.autoPlayVideoExist === true) ? true : false;CNN.VideoPlayer.getLibrary(configObj, callbackObj, isLivePlayer);});/* videodemanddust is a default feature of the injector */CNN.INJECTOR.scriptComplete('videodemanddust');JUST WATCHEDTrump heads west to POTUS-friendly IowaReplayMore Videos ...MUST WATCHTrump heads west to POTUS-friendly Iowa 04:17",
"title" : "Trump defiant as pressure grows",
"url" : "cnn.com/2017/06/19/politics/trump-investigation/index.html"
},
Any help would be greatly appreciated. I've been stuck trying to read this file in for some time and cant figure it out. Thanks!!!

see https://rdrr.io/cran/jsonlite/man/flatten.html
data2 <- fromJSON("so.json", flatten = TRUE)

Related

Json Value access in Jquery

I am getting Json Response from ajax page like this
[{"City":"","Email":["khyatiramaswamy9#gmail.com"],"Father\u2019s Name":"Khyati Ramaswamy","Job_Title":[],"Name":"Khyati Ramaswamy","PERSONAL DETAILS":"Khyati Ramaswamy \n\nSobha Hillview \n\nKanakpura road\n\nBangalore - 560052\n\n+91-9920374975 (M)\n\n\n\n\n\n\n\n\n\n\tOBJECTIVE \t\n\n \n\nI seek to give my best on the work front to grow and explore my skills to contribute to the organization that offers professional growth.\n\n\n\n\tWORK EXPERIENCE\t\n\n\n\nDubai4u Investments 2019\n\n\n\nSales and Operations Manager\n\n\n\nResponsibilities \n\n\u2022 Responsible for overall operations of the company\n\n\u2022 Managing Sales Team \n\n\u2022 Managing overall coordination with Clients\n\n.\n\nHop \u2013 Jump \t\t\t\t\t\t\t\t\t\t2004 - 2006\n\n\n\nI started my own business \u2018Hop \u2013 Jump\u2019 a specialist at event planning and organizing\n\n\n\nResponsibilities\n\n\n\nI was the founder of the Company that specialized in customizing parties and events for Clients \n\nI established a strong network with caterers, decorators, anchors, performing artists, party suppliers that could help set up the event as per the specifications and budgets of the client.\n\nWe generated business through word of mouth, partnering with caterers & decorators to generate leads\n\n\n\n\n\nHathway\t\t\t\t\t\t\t\t\t\t2003 - 2004\n\n\n\nWorked a Public Relations Officer \n\n\n\nResponsibilities\n\n\n\nUndertook collections and follow up \n\n\n\n\n\nNisus Integrated Marketing Solutions Pvt Ltd. Media\t\t\t\t2000 - 2002\n\n\n\nWorked a Business Development Manager \n\n\n\nResponsibilities\n\n\n\nGrow the market for Nisus by working out solutions that establish it as a one destination marketing solutions provider.\n\nDrive not just regular but also new business for Nisus\n\nMarket research to recognize changing requirements and trends to offer better solutions to clients\n\nProactively understanding client requirements and offering integrated marketing solutions \n\nLooking at non convention business opportunities and tapping its potential\n\nEstablish relations with vendors who are more competitive and upbeat\n\n\n\n\n\nNisus Integrated Marketing Solutions Pvt Ltd. Media\t\t\t\t1197 - 1998\n\n\n\nWorked a Sales and development Executive \n\n\n\nResponsibilities\n\n\n\nLead Generation and follow up with potential customers to maximize business opportunities\n\nBuild and manage database to pool in more business \n\nTele marketing to establish and sell Nisus\u2019 marketing solutions across media.\n\n\n\n\n\n\tEDUCATION\t\n\n\n\nQualification: \tPostgraduate Diploma in Advertising and Marketing \n\nFrom: \t\tBharti Vidya Bhavan\u2019s Rajendra Prasad Institute of Communication and Management \t\n\nYear: \t\t2000-2001\n\n\n\nQualification: \tB. Com \n\nFrom: \t\tNagpur University\t\n\nYear: \t\t1999-2000\n\n \n\n\tINTERESTS \t\n\n\n\nReading \n\nEvents Planning and Organizing\n\nTravelling & backpacking\n\nCooking and Nutrition Planning\n\n\n\n\tPERSONAL DETAILS\t\n\n\n\nDate of Birth: 9th November 1979\n\nGender: Female\n\nMarital Status: Married\n\nLanguages Know: English, Guajarati, Hindi\n\nBasic Skills: Word, Power Point\n\nEmail Address- khyatiramaswamy9#gmail.com","Phone":["+91-9920374975"],"Skill":[],"State":"","colleges":[],"pin_code":"560052","spoken_languages":["English","Hindi"],"universities":[]}]
when i can the city value like this -> alert(data.city) it coming like undefined.
Ajax code :
<div class="col-lg-6">
<span class="pf-title">Resume</span>
<div class="pf-field">
<input type="file" name="resume" id="resume" accept=".doc,.docx,.pdf" value="" class="resume"/> <?php if($row['Upload_Resume'] == "" || $row['Upload_Resume'] == "NULL") { ?> Update Resume <?php } else{ ?> <a href="All-resumes/<?php echo $row['Upload_Resume']; ?>" target="blank" class="btn btn-danger" style="font-size: 10px;" >View Or Download Resume</a><?php } ?>
<i class="fa fa-upload"></i>
</div>
</div>
$(document).ready(function(){
$(".resume").on('change', function(){
var name = $("#resume").val();
var fd = new FormData();
var files = $('#resume')[0].files;
if(files.length > 0 ){
fd.append('file',files[0]);
$.ajax({
url: 'get_resume_data.php',
type: 'post',
data: fd,
contentType: false,
processData: false,
success: function(dataa){
var dataVal = JSON.parse( dataa );
alert(dataVal);
alert(dataVal[0].City);
},
});
}else{
alert("Please select a file.");
}
});
});
Ajax Page code:
$filename = $_FILES['file']['name'];
$files =$filename;
$postData = curl_file_create(realpath($files),mime_content_type($files),basename($files));
$data = array('file' => $postData);
$request = curl_init('');
curl_setopt_array($request, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS => $data,
));
$result = curl_exec($request);
curl_close($request);
echo $result;
This is what i have trying to do,Thanks in Advance
In comments you mention
its only alert [object][object] when alert(data),alert(data[0]),but alert(data[0].City) return null value
This is only possible if the sample data you provided in your question is not actually the case (in all scenarios).
However if we go by your sample ajax response, we can test it for valid json by directly assigning it to a variable. Note that in your actual code you wouldn't do this, so this ANSWER is to only illustrate that the json in your sample is valid.
let data = [{"City":"Hello","Email":["khyatiramaswamy9#gmail.com"],"Father\u2019s Name":"Khyati Ramaswamy","Job_Title":[],"Name":"Khyati Ramaswamy","PERSONAL DETAILS":"Khyati Ramaswamy \n\nSobha Hillview \n\nKanakpura road\n\nBangalore - 560052\n\n+91-9920374975 (M)\n\n\n\n\n\n\n\n\n\n\tOBJECTIVE \t\n\n \n\nI seek to give my best on the work front to grow and explore my skills to contribute to the organization that offers professional growth.\n\n\n\n\tWORK EXPERIENCE\t\n\n\n\nDubai4u Investments 2019\n\n\n\nSales and Operations Manager\n\n\n\nResponsibilities \n\n\u2022 Responsible for overall operations of the company\n\n\u2022 Managing Sales Team \n\n\u2022 Managing overall coordination with Clients\n\n.\n\nHop \u2013 Jump \t\t\t\t\t\t\t\t\t\t2004 - 2006\n\n\n\nI started my own business \u2018Hop \u2013 Jump\u2019 a specialist at event planning and organizing\n\n\n\nResponsibilities\n\n\n\nI was the founder of the Company that specialized in customizing parties and events for Clients \n\nI established a strong network with caterers, decorators, anchors, performing artists, party suppliers that could help set up the event as per the specifications and budgets of the client.\n\nWe generated business through word of mouth, partnering with caterers & decorators to generate leads\n\n\n\n\n\nHathway\t\t\t\t\t\t\t\t\t\t2003 - 2004\n\n\n\nWorked a Public Relations Officer \n\n\n\nResponsibilities\n\n\n\nUndertook collections and follow up \n\n\n\n\n\nNisus Integrated Marketing Solutions Pvt Ltd. Media\t\t\t\t2000 - 2002\n\n\n\nWorked a Business Development Manager \n\n\n\nResponsibilities\n\n\n\nGrow the market for Nisus by working out solutions that establish it as a one destination marketing solutions provider.\n\nDrive not just regular but also new business for Nisus\n\nMarket research to recognize changing requirements and trends to offer better solutions to clients\n\nProactively understanding client requirements and offering integrated marketing solutions \n\nLooking at non convention business opportunities and tapping its potential\n\nEstablish relations with vendors who are more competitive and upbeat\n\n\n\n\n\nNisus Integrated Marketing Solutions Pvt Ltd. Media\t\t\t\t1197 - 1998\n\n\n\nWorked a Sales and development Executive \n\n\n\nResponsibilities\n\n\n\nLead Generation and follow up with potential customers to maximize business opportunities\n\nBuild and manage database to pool in more business \n\nTele marketing to establish and sell Nisus\u2019 marketing solutions across media.\n\n\n\n\n\n\tEDUCATION\t\n\n\n\nQualification: \tPostgraduate Diploma in Advertising and Marketing \n\nFrom: \t\tBharti Vidya Bhavan\u2019s Rajendra Prasad Institute of Communication and Management \t\n\nYear: \t\t2000-2001\n\n\n\nQualification: \tB. Com \n\nFrom: \t\tNagpur University\t\n\nYear: \t\t1999-2000\n\n \n\n\tINTERESTS \t\n\n\n\nReading \n\nEvents Planning and Organizing\n\nTravelling & backpacking\n\nCooking and Nutrition Planning\n\n\n\n\tPERSONAL DETAILS\t\n\n\n\nDate of Birth: 9th November 1979\n\nGender: Female\n\nMarital Status: Married\n\nLanguages Know: English, Guajarati, Hindi\n\nBasic Skills: Word, Power Point\n\nEmail Address- khyatiramaswamy9#gmail.com","Phone":["+91-9920374975"],"Skill":[],"State":"","colleges":[],"pin_code":"560052","spoken_languages":["English","Hindi"],"universities":[]}]
alert( data[0].City ); // alerts Hello, not null
I only changed the City property value of [0] to "Hello" as opposed to an empty string. However, even an empty string will not return null.
I didn't want to keep extending comments and provided this answer only to illustrate that something else must be wrong with your code that you don't show.

I'm using bert pre-trained model for question and answering. It's returning correct result but with lot of spaces between the text

I'm using bert pre-trained model for question and answering. It's returning correct result but with lot of spaces between the text
The code is below :
def get_answer_using_bert(question, reference_text):
bert_model = BertForQuestionAnswering.from_pretrained('bert-large-uncased-whole-word-masking-finetuned-squad')
bert_tokenizer = BertTokenizer.from_pretrained('bert-large-uncased-whole-word-masking-finetuned-squad')
input_ids = bert_tokenizer.encode(question, reference_text)
input_tokens = bert_tokenizer.convert_ids_to_tokens(input_ids)
sep_location = input_ids.index(bert_tokenizer.sep_token_id)
first_seg_len, second_seg_len = sep_location + 1, len(input_ids) - (sep_location + 1)
seg_embedding = [0] * first_seg_len + [1] * second_seg_len
model_scores = bert_model(torch.tensor([input_ids]),
token_type_ids=torch.tensor([seg_embedding]))
ans_start_loc, ans_end_loc = torch.argmax(model_scores[0]), torch.argmax(model_scores[1])
result = ' '.join(input_tokens[ans_start_loc:ans_end_loc + 1])
result = result.replace('#', '')
return result
Followed by code below :
reference_text = 'Mukesh Dhirubhai Ambani was born on 19 April 1957 in the British Crown colony of Aden (present-day Yemen) to Dhirubhai Ambani and Kokilaben Ambani. He has a younger brother Anil Ambani and two sisters, Nina Bhadrashyam Kothari and Dipti Dattaraj Salgaonkar. Ambani lived only briefly in Yemen, because his father decided to move back to India in 1958 to start a trading business that focused on spices and textiles. The latter was originally named Vimal but later changed to Only Vimal His family lived in a modest two-bedroom apartment in Bhuleshwar, Mumbai until the 1970s. The family financial status slightly improved when they moved to India but Ambani still lived in a communal society, used public transportation, and never received an allowance. Dhirubhai later purchased a 14-floor apartment block called Sea Wind in Colaba, where, until recently, Ambani and his brother lived with their families on different floors.'
question = 'What is the name of mukesh ambani brother?'
get_answer_using_bert(question, reference_text)
And the output is :
'an il am ban i'
Can anyone help me how to fix this issue. It would be really helpful.
You can just use the tokenizer decode function:
bert_tokenizer.decode(input_ids[ans_start_loc:ans_end_loc +1])
Output:
'anil ambani'
In case you do not want to use decode, you can use:
result.replace(' ##', '')

Exception: The number of rows in the range must be at least 1

I am having trouble writing my json data to a google sheet - I get the exception "The number of rows in the data does not match the number of rows in the range."
I think the problem is with how the range is set - but I don't know how to fix it. I include a sample of the json data after this script:
function getApi() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("Sheet1");
var url = "https://www.lexology.com/api/v1/track/clients/articles?companyId=1013419&limit=100";
var params = {
"contentType": "application/json",
"headers":{"ApiKey": "MYAPIKEY"
},
};
var response = UrlFetchApp.fetch(url, params);
var dataAll = JSON.parse(response.getContentText());
var dataSet = dataAll;
var rows = [],
data;
for (i = 0; i < dataSet.length; i++) {
data = dataSet[i];
rows.push([data.companyID, data.companyName, data.articles ]);
}
Logger.log(dataSet)
dataRange = sheet.getRange(3, 1, rows.length, 3);
dataRange.setValues(rows);
}
The json data looks like this:
{
"companyId": 1013419,
"companyName": "Cisco Systems Inc",
"jurisdictions": [],
"workAreas": [],
"tags": [],
"fromDate": "2021-01-10T00:00:00+00:00",
"toDate": "2021-02-10T00:00:00+00:00",
"articles": [
{
"date": "2021-01-04T00:00:00",
"articleUrl": "https://www.lexology.com/library/detail.aspx?g=253372ab-8cce-47c9-853f-4a9953becc0d",
"title": "USPTO and IMPI Announce Parallel Patent Grant Initiative",
"summary": "Under the terms of the MoU, a parallel patent grant framework was instituted which allowed IMPI to leverage search and examination results from the USPTO when issuing a counterpart Mexican patent.",
"firmName": "Casimir Jones SC",
"topic": null,
"jurisdictions": [
"Mexico",
"USA"
],
"workAreas": [
"Patents"
],
"reads": 3,
"prints": 0,
"authorNameOrPhotoClick": 0,
"articleContentLink": 0,
"forwardedUsingMailTo": 0,
"viewOriginal": 0
},
{
"date": "2020-12-23T00:00:00",
"articleUrl": "https://www.lexology.com/library/detail.aspx?g=2c23065f-8479-4343-a889-2a072465bedc",
"title": "Why Everyone Is Patenting Software Inventions",
"summary": "Finding the correct balance requires the assistance of a patent strategist with knowledge of what the patent examiner is likely to accept, and who is skilled in crafting the patent in a way that covers what competitors will need in order to compete.",
"firmName": "Finnegan, Henderson, Farabow, Garrett & Dunner, LLP",
"topic": null,
"jurisdictions": [
"USA"
],
"workAreas": [
"IT & Data Protection",
"Patents"
],
"reads": 3,
"prints": 0,
"authorNameOrPhotoClick": 0,
"articleContentLink": 0,
"forwardedUsingMailTo": 0,
"viewOriginal": 0
}
............EDIT.........
I have fixed the typos in the code as pointed out, thank you.
The output I am looking for is set out in this sheet:
https://docs.google.com/spreadsheets/d/1c3_7D7KOwzR6mPNhKuCoGMNXODr9zgQG7qLzmpFfq6E/edit#gid=0&range=A1:F16
ALSO - when I do Logger.log(dataAll) it is not empty. I get the following:
12:58:42 AM Info Logging output too large. Truncating output. {workAreas=[], articles=[{jurisdictions=[Mexico, USA], forwardedUsingMailTo=0.0, topic=null, prints=0.0, date=2021-01-04T00:00:00, authorNameOrPhotoClick=0.0, viewOriginal=0.0, workAreas=[Patents], title=USPTO and IMPI Announce Parallel Patent Grant Initiative, firmName=Casimir Jones SC, summary=Under the terms of the MoU, a parallel patent grant framework was instituted which allowed IMPI to leverage search and examination results from the USPTO when issuing a counterpart Mexican patent., reads=3.0, articleContentLink=0.0, articleUrl=https://www.lexology.com/library/detail.aspx?g=253372ab-8cce-47c9-853f-4a9953becc0d}, {articleUrl=https://www.lexology.com/library/detail.aspx?g=2c23065f-8479-4343-a889-2a072465bedc, authorNameOrPhotoClick=0.0, prints=0.0, jurisdictions=[USA], viewOriginal=0.0, topic=null, date=2020-12-23T00:00:00, reads=3.0, firmName=Finnegan, Henderson, Farabow, Garrett & Dunner, LLP, forwardedUsingMailTo=0.0, articleContentLink=0.0, summary=Finding the correct balance requires the assistance of a patent strategist with knowledge of what the patent examiner is likely to accept, and who is skilled in crafting the patent in a way that covers what competitors will need in order to compete., title=Why Everyone Is Patenting Software Inventions, workAreas=[IT & Data Protection, Patents]}, {date=2021-01-12T00:00:00, prints=0.0, reads=3.0, title=Election Ballot Verification - A Patent Subject Matter Eligibility Analysis, summary=v. CLS Bank Int., the court (1) determined that the claims were drawn to an abstract idea of “voting, verifying the vote, and submitting the vote for tabulation” and (2) found “no inventive concept in the claims sufficient to transform them into patent-eligible subject matter.” Recited at a high level of abstraction, the claims at issue before the court included one or more voting stations, each including a computer, a display, a printer, an input device, a ballot scanning machine, and a means for tabulating printed ballots., workAreas=[Litigation, Patents], jurisdictions=[USA], authorNameOrPhotoClick=0.0, forwardedUsingMailTo=0.0, topic=null, viewOriginal=0.0, articleContentLink=0.0, articleUrl=https://www.lexology.com/library/detail.aspx?g=544fc695-b8eb-4951-a19e-c2df4b7039b6, firmName=Baker & Hostetler LLP}, {authorNameOrPhotoClick=0.0, topic=null, forwardedUsingMailTo=0.0, date=2021-02-04T00:00:00, reads=3.0, articleUrl=https://www.lexology.com/library/detail.aspx?g=64b1aa84-d37f-4e80-9805-3509b48c1824, workAreas=[IT & Data Protection, Litigation], jurisdictions=[USA], title=Successful Dismissal of PayPal Class Action Over Breach Disclosures Serves as Risks Reminder, summary=Companies should consult closely with counsel when making a public announcement regarding a potential or confirmed data security incident to ensure they are thinking through the potential regulatory and litigation risks, whether a trading blackout period is appropriate during the period of investigation, and whether existing cybersecurity risk disclosures in the company’s public filings should be amended., firmName=Sheppard Mullin Richter & Hampton LLP, articleContentLink=0.0, prints=0.0, viewOriginal=0.0}, {topic=null, firmName=Wilmer Cutler Pickering Hale and Dorr LLP, articleUrl=https://www.lexology.com/library/detail.aspx?g=6cad7e90-ff4a-413f-9a4d-079a23c12a44, prints=0.0, reads=3.0, date=2020-12-22T00:00:00, title=Quick Takeaways: SolarWinds Cybersecurity Incident, viewOriginal=0.0, authorNameOrPhotoClick=0.0, articleContentLink=0.0, forwardedUsingMailTo=0.0, workAreas=[IT & Data Protection], summary=Certain versions of SolarWinds software updates that assist organizations in managing their computer networks were compromised by what some officials, such as the US Secretary of State and the US Attorney General, have indicated is a Russian intelligence agency., jurisdictions=[USA]}, {firmName=Reed Smith LLP, forwardedUsingMailTo=0.0, authorNameOrPhotoClick=0.0, summary=The Guidelines set out the law applicable to operations consisting in reading or writing data on users’ devices and clarify the CNIL’s approach, while the Recommendation aims to guide organisations in their compliance efforts by providing examples of practical methods that can be used, notably to collect consent., date=2021-01-22T00:00:00, title=Adtech regulatory round-up January 2021, articleUrl=https://www.lexology.com/library/detail.aspx?g=8973269a-306a-48d3-9b19-0e50a6647d96, articleContentLink=0.0, viewOriginal=1.0, jurisdictions=[Germany, France, United Kingdom, USA], topic=null, workAreas=[IT & Data Protection, Litigation], reads=3.0, prints=0.0}, {firmName=Sheppard Mullin Richter & Hampton LLP, reads=3.0, articleUrl=https://www.lexology.com/library/detail.aspx?g=8e3a8f46-982e-41ba-a4bc-9e8af57ac7db, forwardedUsingMailTo=0.0, summary=The second carve-out from the definition of protected information was for information known to the employee before he joined TGS, “as evidenced by Employee’s written records.” The Brown court took a particularly dim view of this exception, because it would mean that information which, by definition was not confidential before Brown began working at TSG, would become so unless Brown had written records proving he knew of it beforehand., authorNameOrPhotoClick=0.0, title=California Court Strikes Down Overbroad Confidentiality Agreement as a de facto Non-Compete, articleContentLink=0.0, prints=0.0, topic=null, viewOriginal=0.0, date=2021-01-05T00:00:00, workAreas=[Employment & Labor, Litigation], jurisdictions=[USA]},
Issue:
Apparently you can't get a range with 0 rows. In this method getRange(row, column, numRows, numColumns), every parameter should be a number larger than 0.
Why is rows.length 0?
The issue has to do with the fact that your JSON dataSet is not an array, therefore the for loop is terminated because dataSet.length is undefined. As a result row.length is zero because no values were added.
Updated Solution:
Assuming the first row (headers) in your sheet is:
companyId companyName articles.date articles.articleUrl articles.title articles.summary
function getApi() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName("Sheet1");
const url = "https://www.lexology.com/api/v1/track/clients/articles?companyId=1013419&limit=100";
const params = {
"contentType": "application/json",
"headers":{"ApiKey": "MYAPIKEY"
},
};
const response = UrlFetchApp.fetch(url, params);
const dataSet = JSON.parse(response.getContentText());
const data =
dataSet.articles.map((r,i)=>
i==0?[dataSet.companyId,dataSet.companyName,r.date,r.articleUrl,r.title,r.summary]:
["","",r.date,r.articleUrl,r.title,r.summary]
);
sheet.getRange(sheet.getLastRow()+1,1,data.length,data[0].length).setValues(data);
}
The simplest solution is to move the line from fig1the line under the first row to fig2the line under the second row. It works for me!

Sentence-count function not returning total count

So i've been trying to create a sentence-count function which will cycle through the following 'story':
let story = 'Last weekend, I took literally the most beautiful bike ride of my life. The route is called "The 9W to Nyack" and it actually stretches all the way from Riverside Park in Manhattan to South Nyack, New Jersey. It\'s really an adventure from beginning to end! It is a 48 mile loop and it basically took me an entire day. I stopped at Riverbank State Park to take some extremely artsy photos. It was a short stop, though, because I had a really long way left to go. After a quick photo op at the very popular Little Red Lighthouse, I began my trek across the George Washington Bridge into New Jersey. The GW is actually very long - 4,760 feet! I was already very tired by the time I got to the other side. An hour later, I reached Greenbrook Nature Sanctuary, an extremely beautiful park along the coast of the Hudson. Something that was very surprising to me was that near the end of the route you actually cross back into New York! At this point, you are very close to the end.';
And I realise the problem I'm having but I cannot find a way around this. Basically I want my code to return a the total sCount below but seeing as I've returned my sCount after my loop, it's only adding and returning the one count as a total:
const sentenceTotal = (word) => {
let sCount = 0;
if (word[word.length-1] === "." || word[word.length-1] === "!" || word[word.length-1] === "?") {
sCount += 1;
};
return sCount;
};
// console.log(sentenceTotal(story)) returns '1'.
I've tried multiple ways around this, such as returning sentenceTotal(word) instead of sCount but console.log will just log the function name.
I can make it return the correct sCount total if I remove the function element of it, but that's not what I want.
I don't see any loop or iterator which would go through story to count the number of occurrences of ., ?, or !.
Having recently tackled "counting sentences" myself I know it is a non-trivial problem with many edge cases.
For a simple use-case though you can use split and a regular expression;
story.split(/[?!.]/).length
So you could wrap that in your function like so:
const sentenceTotal = (word) => {
return word.split(/[?.!]/).length
};
let story = 'Last weekend, I took literally the most beautiful bike ride of my life. The route is called "The 9W to Nyack" and it actually stretches all the way from Riverside Park in Manhattan to South Nyack, New Jersey. It\'s really an adventure from beginning to end! It is a 48 mile loop and it basically took me an entire day. I stopped at Riverbank State Park to take some extremely artsy photos. It was a short stop, though, because I had a really long way left to go. After a quick photo op at the very popular Little Red Lighthouse, I began my trek across the George Washington Bridge into New Jersey. The GW is actually very long - 4,760 feet! I was already very tired by the time I got to the other side. An hour later, I reached Greenbrook Nature Sanctuary, an extremely beautiful park along the coast of the Hudson. Something that was very surprising to me was that near the end of the route you actually cross back into New York! At this point, you are very close to the end.';
sentenceTotal(story)
=> 13
There a several strange things about you question so I'll do it in 3 steps :
First step : The syntax.
What you wrote is the assignement to a const of an anonymous variable. So what it does is :
Create a const name 'sentenceCount'
To this const, assign the anonymous function (words) => {...}
Now you have this : sentenceCount(words){...}
And that's all. Because what you wrote : ()=>{} is not the calling of a function, but the declaration of an anonym function, you should read this : https://www.w3schools.com/js/js_function_definition.asp
If you want a global total, you must have a global total variable(not constant) so that the total isn't lost. So :
let sCount = 0; //<-- have sCount as a global variable not a const
function isEndOfSentence(word) {
if (word[word.length-1] === "." || word[word.length-1] === "!" || word[word.length-1] === "?") {
sCount += 1;
};
};
If you are forbidden from using a global variable (and it's best to not do so), then you have to register the total as a return of your function and store the total in the calling 'CountWords(sentence)' function.
function isEndOfSentence(words) {...}
callingFunction(){
//decalaration
let total;
//...inside your loop
total += isEndOfSentence(currentWord)
}
The algorithm
Can you provide more context as how you use you function ?
If your goal is to count the words until there is a delimiter to mark the end of a sentence, your function will not be of great usage .
As it is written, your function will only ever be able to return 0 or 1. As it does the following :
The function is called.
It create a var called sCount and set it to 0
It increment or not sCount
It return sCount so 1 or 0
It's basically a 'isEndOfSentence' function that would return a boolean. It's usage should be in an algorithm like :
// var totalSentence = 0
// for each word
// if(isEndOfSentence(word))
// totalSentence + totalSentence = 1
// endfor
Also this comes back to just counting the punctuation to count the number of sentence.
The quick and small solution
Also I tried specifically to keep the program in an algorithm explicit form since I guess that's what you're dealing with.
But I feel that you wanted to write something small and with as little characters as possible so for your information, there are faster way of doing this with a tool called regex and the native JS 'split(separator)' function of a string.
A regex is a description of a string that it can match to and when used can return those match. And it can be used in JS to split a string:
story.split(/[?!.]/) //<-- will return an array of the sentences of your story.
story.split(/[?!.]/).length //<-- will return the number of element of the array of the sentences of your story, so the sentence count
That does what you wanted but with one line of code. But If you want to be smart about you problem, remember that I said
Also this comes back to just counting the punctuation to count the number of sentence.
So we'll just do that right ?
story.match(/(\.\.\.)|[.?!]/g).length
Have fun here ;) : https://regexr.com/
I hope that helps you ! Good luck !

Flash AS3 trivia game incorrect answer graphic needs to appear on stage in 3 locations

I'm creating a trivia game in which a user answers a certain number of questions per round and if they get 3 wrong they fail the round. When a question is marked as incorrect an x is placed in a box from left to right, each x goes into a box in their own location.
I'm having trouble getting the x's to go to their location, based on the questions answered incorrectly.
Here is an image of the game image
Here is the code I'm using:
var questions:Array=['"I look like a dangling parsnip in this!" she cried. "I will never __________ these jeans!',
"Tell the freckled parrot to put his car in __________.",
"When purchasing a buttercream trowel, always choose one made of __________.",
"Everybody has a cracked snowflake. The question is, __________ one is yours? ",
"Standing at the dock, the loopy basket watched the cruise ship set __________ without him. ",];
var answers:Array=[ ["wear","where"], ["idle","idol"], ["steel","steal"] ,[ "which","witch"] ,[ "sail","sale"] ];
var qno=0;var rnd1; var rnd2;
tick.visible=false;cross1.visible=false;
var right_answers=0;var wrong_answers=0;
shade1.buttonMode = true;
shade1.useHandCursor = true;
shade2.buttonMode = true;
shade2.useHandCursor = true;
function change_question(){
if(tick.visible){right_answers++;}
if(cross1.visible){wrong_answers++;}
if(qno==questions.length){gotoAndPlay(60);}else{
tick.visible=false;cross1.visible=false;
rnd1=Math.ceil(Math.random()*3);
rnd2=Math.ceil(Math.random()*questions.length)-1;
q.text=questions[rnd2];
if(questions[rnd2]=="x"){change_question();}
questions[rnd2]="x";
enable_disable(1);
if(rnd1==1){opt1.text=answers[rnd2][0];opt2.text=answers[rnd2][1];}
if(rnd1==2){opt1.text=answers[rnd2][0];opt2.text=answers[rnd2][1];}
if(rnd1==3){opt1.text=answers[rnd2][0];opt2.text=answers[rnd2][1];}
if(rnd1==4){opt1.text=answers[rnd2][0];opt2.text=answers[rnd2][1];}
if(rnd1==5){opt1.text=answers[rnd2][0];opt2.text=answers[rnd2][1];}
}}
function enable_disable(a){
if(a==0){shade1.mouseEnabled=false;shade2.mouseEnabled=false;}
if(a==1){shade1.mouseEnabled=true;shade2.mouseEnabled=true;}}
change_question();
shade1.addEventListener(MouseEvent.CLICK, ButtonAction2);
shade2.addEventListener(MouseEvent.CLICK, ButtonAction3);
function ButtonAction2(eventObject:MouseEvent) {
enable_disable(0);if(rnd1==1) {tick.visible=true;tick.y=shade1.y}else{cross1.visible=true;cross1.y=shade1.y}
//qno++;change_question();
}
function ButtonAction3(eventObject:MouseEvent) {
enable_disable(0);if(rnd1==2){tick.visible=true;tick.y=shade2.y}else{cross1.visible=true;cross1.y=428.55}
//qno++;change_question();
}
Any help is much appreciated, please let me know if more information is needed. Thank you in advance.