Json Value access in Jquery - json

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.

Related

Converting text to html format in R

I have a dataframe with lots of text data that needs to be formatted into html. Here is one example with sub-bullets. Not all lists have sub-bullets. Sub-bullet sare those that start with o
text <- "• Direct the Department’s technical/analytical activities and drive
collaborative relationships with internal personnel and vendors to improve financial
operations and detect, mitigate and prevent financial risk
• Perform supervisory and managerial responsibilities as leader of the program
o Set direction to ensure goals and objectives align with corporate and division strategy
o Select management and other key personnel; oversee talent development and succession
planning
o Collaborate with executive colleagues to develop and execute corporate initiatives and
department strategy
o Oversee the preparation and execution of department’s Annual Financial Plan and budget
o Manage merit pay in accordance with specified objectives and guidelines
• Perform other duties as assigned"
The formatted version is supposed to look like this.
<ul>
<li>Direct the Department's technical/analytical activities and drive collaborative relationships with internal personnel and vendors to improve financial operations and detect, mitigate and prevent financial risk</li>
<li>Perform supervisory and managerial responsibilities as leader of the program
<ul>
<li>Set direction to ensure goals and objectives align with corporate and division strategy</li>
<li>Select management and other key personnel; oversee talent development and succession planning</li>
<li>Collaborate with executive colleagues to develop and execute corporate initiatives and department strategy</li>
<li>Oversee the preparation and execution of department's Annual Financial Plan and budget</li>
<li>Manage merit pay in accordance with specified objectives and guidelines</li>
</ul>
<li>Perform other duties as assigned</li>
</ul>
The "text" above is an example of the type of data. Some have sub bullets other not.
I have no problem doing the li>, the tricky part is finding the sub-bullets and surrounding them with ul> and /ul>
This code does most of it, but how to I put back into the dataframe dfClean?
# Use the str_split() function from the stringr package to split the text into a list of sentences
for (k in 1:6) {
temp_sentence <- str_split(dfClean[k,24], "\\r\\n")[[1]]
# Find the indices of the sentences starting with <li>o
o_indices <- ifelse(grep("^o", temp_sentence), grep("^o", temp_sentence), 0)
# Use the paste0() function to create the HTML list
html_list <- paste0("<ul>\n")
for (i in 1:length(temp_sentence)) {
if(length(o_indices) > 0){
if (i == o_indices[1]) {
html_list <- paste0(html_list, "\t<ul>\n") # add <ul> before subbullets
}
# add extra tab for sub-bullets
if (i %in% o_indices) {
html_list <- paste0(html_list, "\t\t<li>", temp_sentence[i], "</li>\n")
}
else {
html_list <- paste0(html_list, "\t<li>", temp_sentence[i], "</li>\n")
}
# add </ul> after last sub bullet
if (i == o_indices[length(o_indices)]) {
html_list <- paste0(html_list, "\t</ul>\n")
}
}
else {html_list <- paste0(html_list, "\t<li>", temp_sentence[i], "</li>\n")
}
}
print(k)
html_list <- paste0(html_list, "</ul>\n")
# remove dots
html_list <- gsub("<li>•|<li>o", "<li>", html_list)
# Print the HTML list
cat(html_list)
}

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!

Convert HTML to PDF in Power Automate

I am working on Power Automate and trying to convert an HTML page into a pdf file. However, before the HTML page content loads completely, the conversion process takes place. As a result, the pdf file created is either blank or has a loading symbol.
I believe the need is to add a manual delay of a few seconds between page load and pdf file conversion, but am unable to do so.
Below is the concerned 'definition' file JSON code extracted after exported the Power Automate Flow. The connector for pdf conversion can be searched as "operationId":"ConvertFileByPath"
{"name":"611652cf-aec0-4733-8871-b0f0f40af783","id":"/providers/Microsoft.Flow/flows/611652cf-aec0-4733-8871-b0f0f40af783","type":"Microsoft.Flow/flows","properties":{"apiId":"/providers/Microsoft.PowerApps/apis/shared_logicflows","displayName":"Enterprise
Assessment Tool","definition":{"metadata":{"workflowEntityId":null,"creator":{"id":"4205125c-5d6f-4e96-b565-709e4a8dcbde","type":"User","tenantId":"971f0e31-00d6-4e42-b8e0-47b342bc4455"},"provisioningMethod":"FromDefinition","failureAlertSubscription":true,"clientLastModifiedTime":"2020-03-20T08:55:47.5792257Z"},"$schema":"https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#","contentVersion":"1.0.0.0","parameters":{"$connections":{"defaultValue":{},"type":"Object"},"$authentication":{"defaultValue":{},"type":"SecureObject"}},"triggers":{"When_a_new_response_is_submitted":{"type":"OpenApiConnectionWebhook","inputs":{"host":{"apiId":"/providers/Microsoft.PowerApps/apis/shared_microsoftforms","connectionName":"shared_microsoftforms_2","operationId":"CreateFormWebhook"},"parameters":{"form_id":"MQ4fl9YAQk644EezQrxEVVwSBUJvXZZOtWVwnkqNy95UNkVCVlJZSVlHQlBEWFhOMkFJUE5PT1pSWS4u"},"authentication":"#parameters('$authentication')"}}},"actions":{"Apply_to_each":{"foreach":"#triggerOutputs()?['body/value']","actions":{"Get_response_details":{"runAfter":{},"type":"OpenApiConnection","inputs":{"host":{"apiId":"/providers/Microsoft.PowerApps/apis/shared_microsoftforms","connectionName":"shared_microsoftforms_2","operationId":"GetFormResponseById"},"parameters":{"form_id":"MQ4fl9YAQk644EezQrxEVVwSBUJvXZZOtWVwnkqNy95UNkVCVlJZSVlHQlBEWFhOMkFJUE5PT1pSWS4u","response_id":"#items('Apply_to_each')?['resourceData/responseId']"},"authentication":"#parameters('$authentication')"}},"Add_a_row_into_a_table":{"runAfter":{"Get_response_details":["Succeeded"]},"metadata":{"016AIIWUWO74RBMREYLVAIQPOYYNXRWO3P":"/Enterprise
Assessment Tool.xlsx","tableId":"{9C186D95-CBB6-477E-8699-17B3089A0368}","01BSP3ENPNPETDO5YJUVBI2X6MEG5ARSKV":"/Enterprise Assessment Tool.xlsx"},"type":"OpenApiConnection","inputs":{"host":{"apiId":"/providers/Microsoft.PowerApps/apis/shared_excelonlinebusiness","connectionName":"shared_excelonlinebusiness_1","operationId":"AddRowV2"},"parameters":{"source":"me","drive":"b!wjpSLG6KfES6F9-MfcSm-aeq5llhoTVMpfXuBQBmrywjSt-PswuwSbm1_6BG5sFo","file":"01BSP3ENPNPETDO5YJUVBI2X6MEG5ARSKV","table":"{9C186D95-CBB6-477E-8699-17B3089A0368}","item/ID":"#items('Apply_to_each')?['resourceData/responseId']","item/Your
name":"#outputs('Get_response_details')?['body/r6b6a573a836044eab553ba2e0ab92446']","item/Organization’s Name":"#outputs('Get_response_details')?['body/ra2af29025bff44bbac289f9c61c76666']","item/Your Email Address":"#outputs('Get_response_details')?['body/rf505d38dc6334aa7b69d2c77f230f09e']","item/Providing
clear and effective leadership":"#outputs('Get_response_details')?['body/r4b5eade301884d9b8629c9b38d9a3c2d']","item/Anticipating opportunities and threats to keep us ahead of change":"#outputs('Get_response_details')?['body/rca90ae117bc347f9886072f118ceb630']","item/Willingness
to take on risks for long-term growth, even if that could decrease current year profits":"#outputs('Get_response_details')?['body/rc8656608760f4e19abc1d78ecacbf825']","item/Making disciplined IT investment decisions":"#outputs('Get_response_details')?['body/r14226cb30f604f20a626157ec1786086']","item/Using
IT to gain competitive advantage":"#outputs('Get_response_details')?['body/r963c2865db4d4e90b20fa82547a48c62']","item/Articulating a clear and consistent vision to employees, consumers and partners":"#outputs('Get_response_details')?['body/r01698107f2ea4286a8f59ec20f17f3b8']","item/Enabling
the enterprise to navigate change":"#outputs('Get_response_details')?['body/r2c02b757c2444656a4c32388e2353724']","item/Fostering and changing the culture in IT":"#outputs('Get_response_details')?['body/r09d450406bfb477bb55cfd5dd572eb09']","item/Please
rate the clarity and consistency of your enterprise’s overall business strategy_x002e_":"#outputs('Get_response_details')?['body/r5bdc0ce9ba0b46348149fb2422b4e041']","item/Please indicate the nature of your organization’s CIO’s (or the most senior IT
leader’s) relationship with the CEO (or most senior Business executive)_x002e_":"#outputs('Get_response_details')?['body/r29c1767ce4bd4da6bec697ede635a908']","item/Has your organization faced any of these situations in the past four years? Please select
all that apply_x002e_":"#outputs('Get_response_details')?['body/rb4f8047c739d42938a52145e9a9cbef1']","item/Please share some details regarding the business disruption that you faced in the past four years_x002e_":"#outputs('Get_response_details')?['body/r7652d524e6524ba19fe6c629c4869aa0']","item/External
disruption of your business environment":"#outputs('Get_response_details')?['body/rd3d4bb9074a2411d9234551e0092500c']","item/Adverse regulatory intervention":"#outputs('Get_response_details')?['body/rc01f99fd45e74f5695e7fbcbcd66b6a4']","item/Cyber security
issue":"#outputs('Get_response_details')?['body/reb816f5b028b43ccb22128f0bac6bc00']","item/IT Service failure":"#outputs('Get_response_details')?['body/r95c7899a06e74c04b6a4f96fb905abe8']","item/Product~1service failure":"#outputs('Get_response_details')?['body/r15ea7200480b45febe0384a5ad4fe683']","item/Operating
cost pressure":"#outputs('Get_response_details')?['body/r952f66721ebf48b6bb9e23f64273ae6a']","item/Labor disruption":"#outputs('Get_response_details')?['body/ree57c3756cc04cf8b0d37e158256b1ef']","item/Shifting consumer demand":"#outputs('Get_response_details')?['body/r712b33b666694e80be27b2bcfb4bba86']","item/Funding
shortfall":"#outputs('Get_response_details')?['body/r493be3af3d244d638863da8b4e68fadc']","item/Organizational disruption":"#outputs('Get_response_details')?['body/r90bcccc8a1c3475186f5454677e9199a']","item/Some other disruptive business situation":"#outputs('Get_response_details')?['body/r939f57c83c054ab08d6c64c33bb5c62b']","item/The
overall business performance of the enterprise":"#outputs('Get_response_details')?['body/r729caa64609d4b998cfd200997bdca41']","item/Speed at which new business initiatives are launched":"#outputs('Get_response_details')?['body/r3061360c935d4f0093939e6b64bec6b7']","item/Ability
to fund new business initiatives":"#outputs('Get_response_details')?['body/rb186360b5d6a455d8ed624c1ab6a8ac0']","item/Speed at which business initiatives are successfully completed":"#outputs('Get_response_details')?['body/r3061360c935d4f0093939e6b64bec6b7']","item/Ability
to use data to achieve intended outcomes":"#outputs('Get_response_details')?['body/r2f1fc86f6d6f4cf6a78528bdf5b8e7e2']","item/Ability to attract the right talent to fill our needs":"#outputs('Get_response_details')?['body/rc3a23d40f20f49b78cab3880f0c8db38']","item/Ability
to get value from new business initiatives":"#outputs('Get_response_details')?['body/r4e4371bf1cdc472c8935bc398f7751b5']","item/IT budget growth":"#outputs('Get_response_details')?['body/rc0a78909625144acbc4d9d94658b0c74']","item/Operating cost competitiveness":"#outputs('Get_response_details')?['body/rac841e5b9e064ee88ec84dd54f48e40e']","item/Reputation
as an innovative enterprise":"#outputs('Get_response_details')?['body/r5ebbb6aebc8e4623bf987dca1e01afd1']","item/Our long-term viability":"#outputs('Get_response_details')?['body/rb83eaa31847f4306a54fa6375d5d544d']","item/The stability of the leadership
team (CEO and downward)":"#outputs('Get_response_details')?['body/r7ac35c66284e4215b4dd6ac173134b54']"},"authentication":"#parameters('$authentication')"}}},"runAfter":{},"type":"Foreach"},"Refresh_a_dataset":{"runAfter":{"Delay_2":["Succeeded"]},"type":"OpenApiConnection","inputs":{"host":{"apiId":"/providers/Microsoft.PowerApps/apis/shared_powerbi","connectionName":"shared_powerbi","operationId":"RefreshDataset"},"parameters":{"groupid":"42cf205d-726b-418a-b227-d03cbcaa9f6b","datasetid":"36269b8f-45cd-43c7-a2fa-a3995da63c51"},"authentication":"#parameters('$authentication')"}},"Delay":{"runAfter":{"Refresh_a_dataset":["Succeeded"]},"type":"Wait","inputs":{"interval":{"count":1,"unit":"Minute"}}},"Delay_2":{"runAfter":{"Apply_to_each":["Succeeded"]},"type":"Wait","inputs":{"interval":{"count":1,"unit":"Minute"}}},"Apply_to_each_3":{"foreach":"#triggerOutputs()?['body/value']","actions":{"Get_response_details_3":{"runAfter":{},"type":"OpenApiConnection","inputs":{"host":{"apiId":"/providers/Microsoft.PowerApps/apis/shared_microsoftforms","connectionName":"shared_microsoftforms_2","operationId":"GetFormResponseById"},"parameters":{"form_id":"MQ4fl9YAQk644EezQrxEVVwSBUJvXZZOtWVwnkqNy95UNkVCVlJZSVlHQlBEWFhOMkFJUE5PT1pSWS4u","response_id":"#items('Apply_to_each_3')?['resourceData/responseId']"},"authentication":"#parameters('$authentication')"}},"Convert_HTML_to_PDF":{"runAfter":{"Get_response_details_3":["Succeeded"]},"type":"OpenApiConnection","inputs":{"host":{"apiId":"/providers/Microsoft.PowerApps/apis/shared_encodiandocumentmanager","connectionName":"shared_encodiandocumentmanager","operationId":"HtmlToPDF"},"parameters":{"operation/outputFilename":"Enterprise
Fitness Assessment Report_#{outputs('Get_response_details_3')?['body/ra2af29025bff44bbac289f9c61c76666']}","operation/htmlData":"
<!DOCTYPE html>\n
<html>\n\n
<head>\n
<script>
\
n\ nwindow.addEventListener('load', function() {\
nsetInterval(function() {\
ndocument.getElementById(\"delayedText\").style.visibility = \"visible\";\n},10000);\n\n}, false);\n\n/*window.onload = function(){\n \n var theDelay = 60;\n var timer = setTimeout(\"showText()\",theDelay*1000)\n}\nfunction showText(){\n document.getElementById(\"delayedText\").style.visibility = \"visible\";\n}*/\n\n\n
</script>\n</head>\n\n
<body>\n
<div id=\ "delayedText\" style=\ "visibility:hidden\">This is a test\n\n<iframe width=\ "1140\" height=\ "541.25\" src=\
"https://app.powerbi.com/reportEmbed?reportId=d27f0160-eb09-442b-a7ab-ded938ed33ec&autoAuth=true&ctid=971f0e31-00d6-4e42-b8e0-47b342bc4455&config=eyJjbHVzdGVyVXJsIjoiaHR0cHM6Ly93YWJpLXdlc3QtdXMtcmVkaXJlY3QuYW5hbHlzaXMud2luZG93cy5uZXQvIn0%3D\" frameborder=\ "0\" allowFullScreen=\ "true\"></iframe>\n</div>\n\n</body>\n
</html>","operation/pageOrientation":"Landscape","operation/pageSize":"A4","operation/viewPort":"Default","operation/MarginTop":25,"operation/MarginBottom":25,"operation/MarginRight":25,"operation/MarginLeft":25,"operation/enableBookmarks":true,"operation/enableJavaScript":true,"operation/enableHyperlinks":true,"operation/createPdfForm":false,"operation/decodeHtmlData":true,"operation/cssType":"Screen","operation/repeatTableHeader":true,"operation/repeatTableFooter":true,"operation/splitImages":false,"operation/splitTextLines":false,"operation/encoding":"UTF8","operation/FinalOperation":true},"authentication":"#parameters('$authentication')"}},"Create_file":{"runAfter":{"Convert_HTML_to_PDF":["Succeeded"]},"type":"OpenApiConnection","inputs":{"host":{"apiId":"/providers/Microsoft.PowerApps/apis/shared_onedriveforbusiness","connectionName":"shared_onedriveforbusiness","operationId":"CreateFile"},"parameters":{"folderPath":"/Enterprise
Assessment Reports","name":"#outputs('Convert_HTML_to_PDF')?['body/Filename']","body":"#outputs('Convert_HTML_to_PDF')?['body/FileContent']"},"authentication":"#parameters('$authentication')"},"runtimeConfiguration":{"contentTransfer":{"transferMode":"Chunked"}}},"Send_an_email":{"runAfter":{"Create_file":["Succeeded"]},"type":"OpenApiConnection","inputs":{"host":{"apiId":"/providers/Microsoft.PowerApps/apis/shared_office365","connectionName":"shared_office365","operationId":"SendEmailV2"},"parameters":{"emailMessage/To":"#outputs('Get_response_details_3')?['body/rf505d38dc6334aa7b69d2c77f230f09e']","emailMessage/Subject":"Gartner
Enterprise Fitness Assessment Report","emailMessage/Body":"
<p>Hi #{outputs('Get_response_details_3')?['body/r6b6a573a836044eab553ba2e0ab92446']}<br>\n<br>\nThanks for submitting your response! Please view the attachement for your organisation's assessment.<br>\n<br>\nTeam PRM</p>","emailMessage/From":"Prakhar.Gupta#gartner.com","emailMessage/Attachments":[{"Name":"#outputs('Convert_HTML_to_PDF')?['body/Filename']","ContentBytes":"#outputs('Convert_HTML_to_PDF')?['body/FileContent']"}]},"authentication":"#parameters('$authentication')"}}},"runAfter":{"Send_an_email_(V2)":["Succeeded"]},"type":"Foreach"},"Send_an_email_(V2)":{"runAfter":{"Create_file_3":["Succeeded"]},"type":"OpenApiConnection","inputs":{"host":{"apiId":"/providers/Microsoft.PowerApps/apis/shared_office365","connectionName":"shared_office365","operationId":"SendEmailV2"},"parameters":{"emailMessage/To":"Prakhar.Gupta#gartner.com","emailMessage/Subject":"test","emailMessage/Body":"
<!DOCTYPE html>\n
<html>\n\n
<head>\n
<script>
\
n\ nwindow.addEventListener('load', function() {\
nsetInterval(function() {\
ndocument.getElementById(\"delayedText\").style.visibility = \"visible\";\n},10000);\n\n}, false);\n\n/*window.onload = function(){\n \n var theDelay = 60;\n var timer = setTimeout(\"showText()\",theDelay*1000)\n}\nfunction showText(){\n document.getElementById(\"delayedText\").style.visibility = \"visible\";\n}*/\n\n\n
</script>\n</head>\n\n
<body>\n
<div id=\ "delayedText\" style=\ "visibility:hidden\">This is a test\n\n<iframe width=\ "1140\" height=\ "541.25\" src=\
"https://app.powerbi.com/reportEmbed?reportId=d27f0160-eb09-442b-a7ab-ded938ed33ec&autoAuth=true&ctid=971f0e31-00d6-4e42-b8e0-47b342bc4455&config=eyJjbHVzdGVyVXJsIjoiaHR0cHM6Ly93YWJpLXdlc3QtdXMtcmVkaXJlY3QuYW5hbHlzaXMud2luZG93cy5uZXQvIn0%3D\" frameborder=\ "0\" allowFullScreen=\ "true\"></iframe>\n</div>\n\n</body>\n
</html>"},"authentication":"#parameters('$authentication')"}},"Create_file_2":{"runAfter":{"Delay":["Succeeded"]},"type":"OpenApiConnection","inputs":{"host":{"apiId":"/providers/Microsoft.PowerApps/apis/shared_onedriveforbusiness","connectionName":"shared_onedriveforbusiness","operationId":"CreateFile"},"parameters":{"folderPath":"/Enterprise
Assessment Reports","name":"Test.html","body":"
<!DOCTYPE html>\n
<html>\n\n
<head>\n
<script>
\
n\ nwindow.addEventListener('load', function() {\
nsetInterval(function() {\
ndocument.getElementById(\"delayedText\").style.visibility = \"visible\";\n},10000);\n\n}, false);\n\n/*window.onload = function(){\n \n var theDelay = 60;\n var timer = setTimeout(\"showText()\",theDelay*1000)\n}\nfunction showText(){\n document.getElementById(\"delayedText\").style.visibility = \"visible\";\n}*/\n\n\n
</script>\n</head>\n\n
<body>\n
<div id=\ "delayedText\" style=\ "visibility:hidden\">This is a test\n\n<iframe width=\ "1140\" height=\ "541.25\" src=\
"https://app.powerbi.com/reportEmbed?reportId=d27f0160-eb09-442b-a7ab-ded938ed33ec&autoAuth=true&ctid=971f0e31-00d6-4e42-b8e0-47b342bc4455&config=eyJjbHVzdGVyVXJsIjoiaHR0cHM6Ly93YWJpLXdlc3QtdXMtcmVkaXJlY3QuYW5hbHlzaXMud2luZG93cy5uZXQvIn0%3D\" frameborder=\ "0\" allowFullScreen=\ "true\"></iframe>\n</div>\n\n</body>\n
</html>"},"authentication":"#parameters('$authentication')"},"runtimeConfiguration":{"contentTransfer":{"transferMode":"Chunked"}}},"Delay_3":{"runAfter":{"Create_file_2":["Succeeded"]},"type":"Wait","inputs":{"interval":{"count":3,"unit":"Minute"}}},"Convert_file_using_path":{"runAfter":{"Delay_3":["Succeeded"]},"type":"OpenApiConnection","inputs":{"host":{"apiId":"/providers/Microsoft.PowerApps/apis/shared_onedriveforbusiness","connectionName":"shared_onedriveforbusiness","operationId":"ConvertFileByPath"},"parameters":{"path":"#outputs('Create_file_2')?['body/Path']","type":"PDF"},"authentication":"#parameters('$authentication')"}},"Create_file_3":{"runAfter":{"Convert_file_using_path":["Succeeded"]},"type":"OpenApiConnection","inputs":{"host":{"apiId":"/providers/Microsoft.PowerApps/apis/shared_onedriveforbusiness","connectionName":"shared_onedriveforbusiness","operationId":"CreateFile"},"parameters":{"folderPath":"/Enterprise
Assessment Reports","name":"#outputs('Convert_file_using_path')?['headers/x-ms-file-name']","body":"#outputs('Convert_file_using_path')?['body']"},"authentication":"#parameters('$authentication')"},"runtimeConfiguration":{"contentTransfer":{"transferMode":"Chunked"}}}},"outputs":{},"description":"Track
Microsoft Forms responses in an Excel Online (Business) spreadsheet. The spreadsheet must have columns: SubmissionTime, ResponderEmail."},"connectionReferences":{"shared_microsoftforms_2":{"connectionName":"shared-microsoftform-ff875ca3-62f2-4c71-bed9-8d02ce26ada2","source":"Embedded","id":"/providers/Microsoft.PowerApps/apis/shared_microsoftforms","tier":"NotSpecified"},"shared_excelonlinebusiness_1":{"connectionName":"shared-excelonlinebu-aabd11c2-e15f-4595-a539-d4ffe5ecd544","source":"Embedded","id":"/providers/Microsoft.PowerApps/apis/shared_excelonlinebusiness","tier":"NotSpecified"},"shared_powerbi":{"connectionName":"shared-powerbi-07a589e5-e541-4241-83c7-2e5ba184ec9f","source":"Embedded","id":"/providers/Microsoft.PowerApps/apis/shared_powerbi","tier":"NotSpecified"},"shared_encodiandocumentmanager":{"connectionName":"shared-encodiandocum-29f09c50-052b-4d59-8c60-7876ab0cf806","source":"Embedded","id":"/providers/Microsoft.PowerApps/apis/shared_encodiandocumentmanager","tier":"NotSpecified"},"shared_onedriveforbusiness":{"connectionName":"shared-onedriveforbu-2262692c-87ba-4be3-a32d-febd64f70219","source":"Embedded","id":"/providers/Microsoft.PowerApps/apis/shared_onedriveforbusiness","tier":"NotSpecified"},"shared_office365":{"connectionName":"shared-office365-28369e56-7ed4-431e-9b7b-ba4930b0f010","source":"Embedded","id":"/providers/Microsoft.PowerApps/apis/shared_office365","tier":"NotSpecified"}},"flowFailureAlertSubscribed":false}}
You can use the Run after property on the action to get the HTML.
So once the action return then you convert your PDF

Nested JSON Dataframe

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)