React component doesn't render HTML after submitting checkbox information - html

I am trying to generate some s with some restaurant data based on the information gathered from multiple checkboxed, but for some reason the data is gathered, but the html elements are not generated.
import React, { Component } from "react";
import data from "../../file2.json"
export default class CheckboxList extends Component {
// Selected locations
state = {
locations: [],
// Current restaurants based on selected locations
currentList: []
}
// keeping the selected locations list up to date
onChange = (event) =>{
console.log(event.target.value + " " + event.target.checked);
const isChecked = event.target.checked;
if (isChecked)
{
this.setState({ locations: [...this.state.locations, event.target.value] });
}
else
{
let index = this.state.locations.indexOf(event.target.value);
this.state.locations.splice(index, 1);
this.setState({ locations: this.state.locations });
}
}
// update the restaurant list accord to each filter detail
onClick = (event) =>{
event.preventDefault();
const res = data;
const final = res.filter((value) => this.state.locations.includes(value.restaurant.location.locality));
this.setState({
currentList: [...this.state.currentList, final],
});
}
render() {
const valuesContainer = this.props.valuesContainer;
return (
<div>
<form>
{
valuesContainer.map((element) => (
<div>
<input type="checkbox" name="locations" value={element.restaurant.location.locality} onChange={this.onChange}></input>
<label>{element.restaurant.location.locality}</label>
</div>
))}
<button class="btn btn-primary" type="submit" onClick={this.onClick} value={valuesContainer}>Apply</button>
<div>
{
this.state.currentList.map((element) => (
<div>
{element.restaurant.location.locality}
</div>
))}
</div>
</form>
</div>
);
}
}
An interesting thing is that if I try to print simple text, without fetching data from the list populated by checkboxes, the divs are generated, but when I try to generate them based on the list, nothing is created.
The data set has the following structure:
[
{
"restaurant": {
"R": {
"res_id": 16668008
},
"apikey": "10a35f36f5898432823df42bc743c8aa",
"id": "16668008",
"name": "Arigato Sushi",
"url": "https://www.zomato.com/yorkton-sk/arigato-sushi-yorkton?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"location": {
"address": "14 Second Ave North, Yorkton, SK S3N 1G1",
"locality": "Yorkton",
"city": "Yorkton",
"city_id": 3600,
"latitude": "51.2106824000",
"longitude": "-102.4613173000",
"zipcode": "S3N 1G1",
"country_id": 37,
"locality_verbose": "Yorkton, Yorkton"
},
"switch_to_order_menu": 0,
"cuisines": "Asian",
"average_cost_for_two": 25,
"price_range": 2,
"currency": "$",
"offers": [],
"thumb": "",
"user_rating": {
"aggregate_rating": "3.3",
"rating_text": "Average",
"rating_color": "CDD614",
"votes": "26"
},
"photos_url": "https://www.zomato.com/yorkton-sk/arigato-sushi-yorkton/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
"menu_url": "https://www.zomato.com/yorkton-sk/arigato-sushi-yorkton/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
"featured_image": "",
"has_online_delivery": 0,
"is_delivering_now": 0,
"deeplink": "zomato://restaurant/16668008",
"has_table_booking": 0,
"events_url": "https://www.zomato.com/yorkton-sk/arigato-sushi-yorkton/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"establishment_types": []
}
},
{
"restaurant": {
"R": {
"res_id": 801690
},
"apikey": "10a35f36f5898432823df42bc743c8aa",
"id": "801690",
"name": "Mocha",
"url": "https://www.zomato.com/lucknow/mocha-gomti-nagar?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"location": {
"address": "CP-1, 2nd Floor, Anand Plaza, Viram Khand-1, Near Patrakarpuram Crossing, Gomti Nagar, Lucknow",
"locality": "Gomti Nagar",
"city": "Lucknow",
"city_id": 8,
"latitude": "26.8528099000",
"longitude": "81.0011849000",
"zipcode": "226010",
"country_id": 1,
"locality_verbose": "Gomti Nagar, Lucknow"
},
"switch_to_order_menu": 0,
"cuisines": "Cafe, Italian, Continental",
"average_cost_for_two": 800,
"price_range": 3,
"currency": "Rs.",
"offers": [],
"thumb": "https://b.zmtcdn.com/data/pictures/0/801690/fa778a9be95f95e7d9846e23b59c8d1a_featured_v2.jpg",
"user_rating": {
"aggregate_rating": "4.6",
"rating_text": "Excellent",
"rating_color": "3F7E00",
"votes": "567"
},
"photos_url": "https://www.zomato.com/lucknow/mocha-gomti-nagar/photos?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1#tabtop",
"menu_url": "https://www.zomato.com/lucknow/mocha-gomti-nagar/menu?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1&openSwipeBox=menu&showMinimal=1#tabtop",
"featured_image": "https://b.zmtcdn.com/data/pictures/0/801690/fa778a9be95f95e7d9846e23b59c8d1a_featured_v2.jpg",
"has_online_delivery": 0,
"is_delivering_now": 0,
"deeplink": "zomato://restaurant/801690",
"has_table_booking": 0,
"events_url": "https://www.zomato.com/lucknow/mocha-gomti-nagar/events#tabtop?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"establishment_types": []
}
},
]

Related

delete object from nested document in mongodb

I have this JSON above with _id, date, and two objects: sessionData and metaData. I want to delete from every document the object metaData where "userId":123456
{
"_id": {
"$oid": "60feedd4b3aefff2629b93b7"
},
"insertionDate": {
"$date": "2021-07-26T18:15:57.564Z"
},
"sessionData": {
"time": [1364, 1374, 1384],
"yaw": [0.15, 0.3, 0.45],
"pitch": [0.36, 0.76, 1.08],
"roll": [-0.13, -0.25, -0.35],
"heading": [-3.24, -3.25, -3.17],
"ax": [-0.42, -0.41, -0.41],
"ay": [-0.15, -0.13, -0.1],
"az": [0.9, 0.91, 1],
"gx": [0, 0, 0],
"gy": [-0.01, 0, -0.01],
"gz": [0.02, 0.02, 0.02],
"mx": [0.26, 0.26, 0.26],
"my": [0.01, 0.01, 0.01],
"mz": [-0.04, -0.04, -0.07]
},
"metaData": {
"userId": 123456,
"gender": "M",
"ageGroup": "SENIOR",
"weightKg": 70,
"heightCm": 175,
"poolSizeM": 50
}
}
The code I have:
#app.route('/data/anonymousData/<int:l>', methods = ['POST'])
def makeanonymous(l):
result = collection.update_many({}, {"$pull":{ "metaData": {"$in": {"userId": l }}}}, multi=True )
t=result.deleted_count
return f'Deleted {t} documents.'
You can use $unset to remove the object like this:
collection.update_many({
"metaData.userId": 123456
},
{
"$unset": {
"metaData": ""
}
})
Check this example.

Unable to get the length of JSON object

I am getting 'TypeError: Cannot convert undefined or null to object' while trying to access the length of json object in nodejs.
Following is how my data looks like:
{
"college": [
{
"colleges": [],
"department": [
1,
2,
3
],
"general_course": [],
"id": 1,
"name": "College of the Arts",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1919"
},
{
"colleges": [],
"department": [
4,
5,
6
],
"general_course": [],
"id": 2,
"name": "College of Communications",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1920"
},
{
"colleges": [],
"department": [
7,
12
],
"general_course": [],
"id": 3,
"name": "College of Education",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1921"
},
{
"colleges": [],
"department": [
13,
17,
19
],
"general_course": [],
"id": 4,
"name": "College of Engineering and Computer Science",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1922"
},
{
"colleges": [],
"department": [
20,
26,
27
],
"general_course": [],
"id": 5,
"name": "College of Health and Human Development",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1923"
},
{
"colleges": [],
"department": [
28,
29,
32,
48
],
"general_course": [],
"id": 6,
"name": "College of Humanities and Social Sciences",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1924"
},
{
"colleges": [],
"department": [
52,
57
],
"general_course": [],
"id": 7,
"name": "College of Natural Sciences and Mathematics",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1925"
},
{
"colleges": [],
"department": [
58,
59,
63
],
"general_course": [],
"id": 8,
"name": "Mihaylo College of Business and Economics",
"short_name": "",
"url": "/content.php?catoid=16&navoid=1926"
}
]
}
Step 1 - Parsing it into nodejs:
let colleges = JSON.parse(data)
Step 2 - Saving it into the dialogflow app data:
app.data.collegeData = data;
Step 3 - Accessing the length:
let collegeLength = Object.keys(app.data.collegeData.college).length;
Getting following error in firebase console:
TypeError: Cannot convert undefined or null to object
Update:
Here is the code:
if ( app.data.collegeData === undefined ){
app.data.collegeData = [];
}
**Step 1 =>**
showColleges(college);
**Step 2 =>**
function showColleges(collegeName){
if (app.data.collegeData.length === 0){
getCollegeData().then(buildSingleCollegeResponse(collegeName))
.catch(function (err){
console.log('No college data')
console.log(err)
});
}
else{
buildSingleCollegeResponse(collegeName);
}
}
**Step 3 =>**
function getCollegeData(){
console.log('Inside get College Data')
return requestAPI(URL)
.then(function (data) {
let colleges = JSON.parse(data)
if (colleges.hasOwnProperty('college')){
saveData(colleges)
}
return null;
})
.catch(function (err) {
console.log('No college data')
console.log(err)
});
}
**Step 4 =>**
function saveData(data){
app.data.collegeData = data;
console.log(app.data.collegeData)
}
**Step 5 =>**
function buildSingleCollegeResponse(collegeName){
let responseToUser, text;
//console.log('Data is -> '+ Object.keys(app.data.collegeData.college).length);
//console.log('Length is -> '+ app.data.collegeData.college.length);
console.log('Count is -> '+app.data.collegeCount);
let collegeLength = Object.keys(app.data.collegeData.college).length;
if ( collegeLength === 0){
responseToUser = 'No colleges available at this time';
text = 'No colleges available at this time';
}
else if ( app.data.collegeCount < collegeLength ){
for ( var i = 1; i <= collegeLength; i++)
{
console.log('All Colleges:: '+app.data.collegeData.college[i])
let coll = app.data.collegeData.college[i]
let name = coll.name
console.log('checkCollegeExist => College Name:: '+ name)
console.log('checkCollegeExist => Parameter => College Name:: '+collegeName)
if(String(name).valueOf() === String(collegeName).valueOf()){
responseToUser = 'Yes! CSUF has '+collegeName;
text = 'Yes! CSUF has '+collegeName;
}else{
responseToUser = 'CSUF does not teach ' +collegeName+' currently';
text = 'CSUF does not teach ' +collegeName+' currently';
}
}
}
else{
responseToUser = 'No more colleges';
}
if (requestSource === googleAssistantRequest) {
sendGoogleResponse(responseToUser);
} else {
sendResponse(text);
}
}
This is the culprit:
getCollegeData().then(buildSingleCollegeResponse(collegeName))
That calls buildSingleCollegeResponse(collegeName) and then passes its return value into then, just like foo(bar()) calls bar and passes its return value into foo.
You wanted to pass a functon to then:
getCollegeData().then(() => buildSingleCollegeResponse(collegeName))
// An arrow function ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Note that now that it's clear from the updated question that app.data.collegeData.college is an array, there's no need for Object.keys. Change:
let collegeLength = Object.keys(app.data.collegeData.college).length;
to simply
let collegeLength = app.data.collegeData.college.length;
Arrays have a length property (whereas non-array objects don't, by default).
You haven't mentioned what value app.data holds before issuing app.data.collegeData = data;
If app.data is undefined you should try app.data = {collegeData: data}
Or else negating what app stores. Following works
app = {};
app.data = {};
app.data.collegeData = data;
app.data.collegeData.college.length
You don't need to do the following
let collegeLength = Object.keys(app.data.collegeData.college).length;
Update: Refer to https://jsfiddle.net/dmxuum79/3/

I am trying to create cascading drop down from json data using Angular JS

I am trying to create cascading drop down from json data using Angular JS but not able to populate data on second dropdown based on Item you select on first drown.
Can any one sugeest me where i am doing mistake
HTML:
<select ng-model="asset 1" id="assetNameGroup" ng-change="populateSection(this)" ng-options=" x.name for x in Nameitems">
<option value="">Select Name</option>
</select>
<select ng-model="asset2" id="assetNameGroup2" ng- change="populateSection2()" ng-options=" x.name for x in asset1.sections">
<option value="">Select Name</option>
</select>
JS
// Code goes here
var app = angular.module("myApp" ,[]);
app.controller('sensorsCtrl', function($scope, $state, $http)
alert("");
$http.get(sample.json).success(function (resp) {
$scope.innerIsIsLoading = false;
$scope.assetData = resp;
$scope.Nameitems = [];
var testobj = $scope.assetData[0].name;
angular.forEach($scope.assetData, function(val,key) {
$scope.Nameitems.push ({"name":
val.name,"uri":val.uri,"sections": val.sections});
console.log("console.log(JSON.stringify-----= "+JSON.stringify
($scope.Nameitems));
});
console.log("$scope.assetData"+JSON.stringify($scope.assetData));
$timeout(function() {
//$scope.SequenceLinkTableData=$scope.assetData;
}, 100);
});
$scope.populateSection=function(value)
{
var checkvalue = value;
console.log(value);
var Namesite = document.getElementById('assetNameGroup').value.split("/")[2];
alert(Namesite);
}
});
Json:
[{
"uri": "/assets/0ff042ea-45e6-32e1-915b-81efa58e924e",
"name": "Asset 1",
"sections": [{
"uri": "/assets/67dc7db3-2374-314d-8b19-6be09d4203c9",
"sectionId": null,
"name": "Section 1",
"ultrasonicSensors": null,
"temperatureSensors": null,
"ultrasonicSensorPositions": [{
"ultrasonicSensorPositionId": 1392,
"sensorPositionName": "MeasurementPosition 1",
"diameter": 12,
"rotation": 270,
"sequenceNumber": null,
"sectionId": "/assets/67dc7db3-2374-314d-8b19-6be09d4203c9"
}, {
"ultrasonicSensorPositionId": 1428,
"sensorPositionName": "MeasurementPosition 2",
"diameter": 12,
"rotation": 270,
"sequenceNumber": null,
"sectionId": "/assets/67dc7db3-2374-314d-8b19-6be09d4203c9"
}]
}, {
"uri": "/assets/8d2c61f7-eb3e-3170-9e0b-dc26b2b574f5",
"sectionId": null,
"name": "Section 1",
"ultrasonicSensors": null,
"temperatureSensors": null,
"ultrasonicSensorPositions": [{
"ultrasonicSensorPositionId": 1390,
"sensorPositionName": "ultrasonic sensor position 1",
"diameter": 22.5,
"rotation": 90,
"sequenceNumber": null,
"sectionId": "/assets/8d2c61f7-eb3e-3170-9e0b-dc26b2b574f5"
}, {
"ultrasonicSensorPositionId": 1427,
"sensorPositionName": "MeasurementPosition 2",
"diameter": 12,
"rotation": 270,
"sequenceNumber": null,
"sectionId": "/assets/8d2c61f7-eb3e-3170-9e0b-dc26b2b574f5"
}, {
"ultrasonicSensorPositionId": 1445,
"sensorPositionName": "MeasurementPosition 3",
"diameter": 12,
"rotation": 270,
"sequenceNumber": null,
"sectionId": "/assets/8d2c61f7-eb3e-3170-9e0b-dc26b2b574f5"
}]
}]
}]
plunker link
In the second ng-options, change from asset1.sections to just asset1:
ng-options="x.name for x in asset1"
Demo: https://plnkr.co/edit/r3zrGrAT4PweKw1aLpe6?p=preview

trouble with parseing JSON with ASPJSON for classic ASP

I am using ASP JSON at http://www.aspjson.com/
I am trying to parse the salehistory the out of this JSON response below. I can get all the nodes under the property object like this
oJSON.data("property").item(0).item("vintage").item("lastModified")
However when I try to go deeper I get errors
I have tried
oJSON.data("property").item(0).item("salehistory").item("salesearchdate") but that does not return anything.
I think that it has something to do with the fact that property is an object and SalesHistory is an object inside of Property however I cannot seem to get the values out of the salehistory level.
Below is the JSON structure that I am trying to parse. Any help would be appreciated. .
{
"status": {
"version": "1.0.0",
"code": 0,
"msg": "SuccessWithResult",
"total": 1,
"page": 1,
"pagesize": 10
},
"property": [
{
"identifier": {
"obPropId": 3464768712115,
"fips": "12115",
"apn": "0283080001",
"apnOrig": "0283080001"
},
"lot": {
"lotSize1": 0.837
},
"address": {
"country": "US",
"countrySubd": "FL",
"line1": "7580 PRESERVATION DR",
"line2": "SARASOTA, FL 34241",
"locality": "Sarasota",
"matchCode": "ExaStr",
"oneLine": "7580 PRESERVATION DR, SARASOTA, FL 34241",
"postal1": "34241",
"postal2": "5201",
"postal3": "R038"
},
"location": {
"accuracy": "Street",
"elevation": 0,
"latitude": "27.267342",
"longitude": "-82.419812",
"distance": 0,
"geoid": "MT30003379,RS0000548079,SD67554,SS156496,SS156498,SS190868"
},
"summary": {
"propclass": "Single Family Residence / Townhouse",
"propsubtype": "SINGLE FAMILY",
"proptype": "SFR",
"yearbuilt": 2005,
"propLandUse": "SFR"
},
"building": {
"size": {
"universalsize": 4256
},
"rooms": {
"bathstotal": 5,
"beds": 4
}
},
"vintage": {
"lastModified": "2015-9-11",
"pubDate": "2015-10-7"
},
"salehistory": [
{
"salesearchdate": "2009-3-30",
"saleTransDate": "2009-3-30",
"amount": {
"saleamt": 1250000,
"salerecdate": "2009-3-30",
"saledisclosuretype": 0,
"saledocnum": "37737",
"saletranstype": "Resale"
},
"calculation": {
"priceperbed": 312500,
"pricepersizeunit": 294
}
},
{
"salesearchdate": "2005-8-9",
"saleTransDate": "2005-8-9",
"amount": {
"saleamt": 185000,
"salerecdate": "2005-8-15",
"saledisclosuretype": 0,
"saledocnum": "181999",
"saletranstype": "Resale"
},
"calculation": {
"priceperbed": 46250,
"pricepersizeunit": 43
}
}
]
}
]
}
Actually I was able to get it figured out.
Since it was a nested object within the property object I need to do the following to access it.
response.write oJSON.data("property").item(0).item("salehistory").item(0).item("amount").item("saleamt"
Adding .item(0) after sales history allowed me to access the salehistory object

How to convert a json file without the same length of json objects into csv

I have a json file and I want to convert it to csv format.
The problem I face is that every json object in the file has not the same length of the converted columns I have. For example the one object have 49 columnns and the next have 50.
I provide here an example of 2 data from which the first one has not the creator.slug but the next has it is and so there is the problem with data. The problem is that the process create all 50 columns but for the object which don't have the value creator.slug it takes the next price.
{
"id": 301852363,
"name": "Song of the Sea",
"blurb": "One evening, two shows: SIRENS and The Girl From Bare Cove. Building a community. Giving voice to survivors of sexual violence.",
"goal": 5000,
"pledged": 671,
"state": "live",
"slug": "song-of-the-sea",
"disable_communication": false,
"country": "US",
"currency": "USD",
"currency_symbol": "$",
"currency_trailing_code": true,
"deadline": 1399293386,
"state_changed_at": 1397133386,
"created_at": 1396672480,
"launched_at": 1397133386,
"backers_count": 20,
"photo": {
"full": "https://s3.amazonaws.com/ksr/projects/939387/photo-full.jpg?1397874930",
"ed": "https://s3.amazonaws.com/ksr/projects/939387/photo-ed.jpg?1397874930",
"med": "https://s3.amazonaws.com/ksr/projects/939387/photo-med.jpg?1397874930",
"little": "https://s3.amazonaws.com/ksr/projects/939387/photo-little.jpg?1397874930",
"small": "https://s3.amazonaws.com/ksr/projects/939387/photo-small.jpg?1397874930",
"thumb": "https://s3.amazonaws.com/ksr/projects/939387/photo-thumb.jpg?1397874930",
"1024x768": "https://s3.amazonaws.com/ksr/projects/939387/photo-1024x768.jpg?1397874930",
"1536x1152": "https://s3.amazonaws.com/ksr/projects/939387/photo-1536x1152.jpg?1397874930"
},
"creator": {
"id": 1714048992,
"name": "Maridee Slater",
"slug": "maridee",
"avatar": {
"thumb": "https://s3.amazonaws.com/ksr/avatars/996153/DSC_0310.thumb.jpg?1337713264",
"small": "https://s3.amazonaws.com/ksr/avatars/996153/DSC_0310.small.jpg?1337713264",
"medium": "https://s3.amazonaws.com/ksr/avatars/996153/DSC_0310.medium.jpg?1337713264"
},
"urls": {
"web": {
"user": "https://www.kickstarter.com/profile/maridee"
},
"api": {
"user": "https://api.kickstarter.com/v1/users/1714048992?signature=1398256877.e6d63adcca055cd041a5920368b197d40459f748"
}
}
},
"location": {
"id": 2459115,
"name": "New York",
"slug": "new-york-ny",
"short_name": "New York, NY",
"displayable_name": "New York, NY",
"country": "US",
"state": "NY",
"urls": {
"web": {
"discover": "https://www.kickstarter.com/discover/places/new-york-ny",
"location": "https://www.kickstarter.com/locations/new-york-ny"
},
"api": {
"nearby_projects": "https://api.kickstarter.com/v1/discover?signature=1398256786.89b2c4539aeab4ad25982694dd7e659e8c12028f&woe_id=2459115"
}
}
},
"category": {
"id": 17,
"name": "Theater",
"slug": "theater",
"position": 14,
"urls": {
"web": {
"discover": "http://www.kickstarter.com/discover/categories/theater"
}
}
},
"urls": {
"web": {
"project": "https://www.kickstarter.com/projects/maridee/song-of-the-sea"
}
}
},
{
"id": 967108708,
"name": "Good Bread Alley",
"blurb": "A play by April Yvette Thompson. A Gullah Healer Woman and an Afro-Cuban Priest forge a new world of magic & dreams in Jim Crow Miami.",
"goal": 100000,
"pledged": 33242,
"state": "live",
"slug": "good-bread-alley",
"disable_communication": false,
"country": "US",
"currency": "USD",
"currency_symbol": "$",
"currency_trailing_code": true,
"deadline": 1399271911,
"state_changed_at": 1396334313,
"created_at": 1393278556,
"launched_at": 1396334311,
"backers_count": 261,
"photo": {
"full": "https://s3.amazonaws.com/ksr/projects/883489/photo-full.jpg?1397869394",
"ed": "https://s3.amazonaws.com/ksr/projects/883489/photo-ed.jpg?1397869394",
"med": "https://s3.amazonaws.com/ksr/projects/883489/photo-med.jpg?1397869394",
"little": "https://s3.amazonaws.com/ksr/projects/883489/photo-little.jpg?1397869394",
"small": "https://s3.amazonaws.com/ksr/projects/883489/photo-small.jpg?1397869394",
"thumb": "https://s3.amazonaws.com/ksr/projects/883489/photo-thumb.jpg?1397869394",
"1024x768": "https://s3.amazonaws.com/ksr/projects/883489/photo-1024x768.jpg?1397869394",
"1536x1152": "https://s3.amazonaws.com/ksr/projects/883489/photo-1536x1152.jpg?1397869394"
},
"creator": {
"id": 749318998,
"name": "April Yvette Thompson",
"avatar": {
"thumb": "https://s3.amazonaws.com/ksr/avatars/9751919/kick_thumb.thumb.jpg?1396128151",
"small": "https://s3.amazonaws.com/ksr/avatars/9751919/kick_thumb.small.jpg?1396128151",
"medium": "https://s3.amazonaws.com/ksr/avatars/9751919/kick_thumb.medium.jpg?1396128151"
},
"urls": {
"web": {
"user": "https://www.kickstarter.com/profile/749318998"
},
"api": {
"user": "https://api.kickstarter.com/v1/users/749318998?signature=1398256877.af4db50c53f93339b05c7813f4534e833eaca270"
}
}
},
"location": {
"id": 2459115,
"name": "New York",
"slug": "new-york-ny",
"short_name": "New York, NY",
"displayable_name": "New York, NY",
"country": "US",
"state": "NY",
"urls": {
"web": {
"discover": "https://www.kickstarter.com/discover/places/new-york-ny",
"location": "https://www.kickstarter.com/locations/new-york-ny"
},
"api": {
"nearby_projects": "https://api.kickstarter.com/v1/discover?signature=1398256786.89b2c4539aeab4ad25982694dd7e659e8c12028f&woe_id=2459115"
}
}
},
"category": {
"id": 17,
"name": "Theater",
"slug": "theater",
"position": 14,
"urls": {
"web": {
"discover": "http://www.kickstarter.com/discover/categories/theater"
}
}
},
"urls": {
"web": {
"project": "https://www.kickstarter.com/projects/749318998/good-bread-alley"
}
}
}
Here is the code I run
#open the json file
require(RJSONIO)
require(rjson)
library("rjson")
filename2 <- "C:/Users/Desktop/in.json"
json_data <- fromJSON(file = filename2)
#unlist the json because it has a problem
unlisted <- unlist(unlist(json_data,recursive=FALSE),recursive=FALSE)
use to fill the NA but as I can understand now it is for already existed nulls http://stackoverflow.com/questions/16947643/getting-imported-json-data-into-a-data-frame-in-r/16948174#16948174
unlisted <- lapply(unlisted, function(x) {
x[sapply(x, is.null)] <- NA
unlist(x)
})
json <- do.call("rbind", unlisted)
Here is a full list with the columns of the output csv and after that I provide what I would like to keep from every object of json, less columns
id
name
blurb
goal
pledged
state
slug
disable_communication
country
currency
currency_symbol
currency_trailing_code
deadline
state_changed_at
created_at
launched_at
backers_count
photo.full
photo.ed
photo.med
photo.little
photo.small
photo.thumb
photo.1024x768
photo.1536x1152
creator.id
creator.name
creator.slug
creator.avatar.thumb
creator.avatar.small
creator.avatar.medium
creator.urls.web.user
creator.urls.api.user
location.id
location.name
location.slug
location.short_name
location.displayable_name
location.country
location.state
location.urls.web.discover
location.urls.web.location
location.urls.api.nearby_projects
category.id
category.name
category.slug
category.position
category.urls.web.discover
category.urls.web.project
category.urls.web.rewards
Here it is the list of columns I would try to have in the output csv:
id
name
blurb
goal
pledged
state
slug
disable_communication
country
currency
currency_symbol
currency_trailing_code
deadline
state_changed_at
created_at
launched_at
backers_count
creator.id
creator.name
creator.slug
location.id
location.name
location.slug
location.short_name
location.displayable_name
location.country
location.state
category.id
category.name
category.slug
category.position
Looks like there's a very similar question (with answer, though not pure R) here: convert json to csv format
However, since you do seem to want most, if not all, the JSON in a "wide CSV" format you can use fromJSON from jsonlite, rbindlist from data.table (which gets you the fill=TRUE parameter to handle uneven lists nicely) and unlist:
library(jsonlite)
library(data.table)
# tell fromJSON we want a list back
json_data <- fromJSON("in.json", simplifyDataFrame=FALSE)
# iterate over the list we have so we can "flatten" it then
# covert it back to a data.frame-like object
dat <- rbindlist(lapply(json_data, function(x) {
as.list(unlist(x))
}), fill=TRUE)
You may need to tweak column names, but I think this gets you what you're looking for.