Parse data from JSON in ReactJS - json

I have data like this:
{
"movies": [
{
"abridged_cast": [
{
"characters": [
"Dominic Toretto"
],
"id": "162652472",
"name": "Vin Diesel"
},
{
"characters": [
"Brian O'Conner"
],
"id": "162654234",
"name": "Paul Walker"
},
{
"characters": [
"Louie Tran"
],
"id": "162684066",
"name": "Tony Jaa"
},
{
"characters": [
"Deckard Shaw"
],
"id": "162653720",
"name": "Jason Statham"
},
{
"characters": [
"Luke Hobbs"
],
"id": "770893686",
"name": "Dwayne \"The Rock\" Johnson"
}
],
"alternate_ids": {
"imdb": "2820852"
},
"critics_consensus": "",
"id": "771354922",
"links": {
"alternate": "http://www.rottentomatoes.com/m/furious_7/",
"cast": "http://api.rottentomatoes.com/api/public/v1.0/movies/771354922/cast.json",
"reviews": "http://api.rottentomatoes.com/api/public/v1.0/movies/771354922/reviews.json",
"self": "http://api.rottentomatoes.com/api/public/v1.0/movies/771354922.json",
"similar": "http://api.rottentomatoes.com/api/public/v1.0/movies/771354922/similar.json"
},
"mpaa_rating": "PG-13",
"posters": {
"detailed": "http://resizing.flixster.com/pVDoql2vCTzNNu0t6z0EUlE5G_c=/51x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/18/14/11181482_ori.jpg",
"original": "http://resizing.flixster.com/pVDoql2vCTzNNu0t6z0EUlE5G_c=/51x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/18/14/11181482_ori.jpg",
"profile": "http://resizing.flixster.com/pVDoql2vCTzNNu0t6z0EUlE5G_c=/51x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/18/14/11181482_ori.jpg",
"thumbnail": "http://resizing.flixster.com/pVDoql2vCTzNNu0t6z0EUlE5G_c=/51x81/dkpu1ddg7pbsk.cloudfront.net/movie/11/18/14/11181482_ori.jpg"
},
"ratings": {
"audience_rating": "Upright",
"audience_score": 88,
"critics_rating": "Certified Fresh",
"critics_score": 82
},
"release_dates": {
"theater": "2015-04-03"
},
"runtime": 140,
"synopsis": "Continuing the global exploits in the unstoppable franchise built on speed, Vin Diesel, Paul Walker and Dwayne Johnson lead the returning cast of Fast & Furious 7. James Wan directs this chapter of the hugely successful series that also welcomes back favorites Michelle Rodriguez, Jordana Brewster, Tyrese Gibson, Chris \"Ludacris\" Bridges, Elsa Pataky and Lucas Black. They are joined by international action stars new to the franchise including Jason Statham, Djimon Hounsou, Tony Jaa, Ronda Rousey and Kurt Russell.",
"title": "Furious 7",
"year": 2015
}
]
}
I need to parse all data from all fields from this JSON file. Is there a way to do it in React JS? Could you please suggest me any way to parse data from a structured JSON file like this?

React lives in JavaScript. So parsing a JSON string is done with:
var myObject = JSON.parse(myjsonstring);
How to fetch a file from somewhere with AJAX is a different question.
You could use fetch() for this. See for example
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API or
https://davidwalsh.name/fetch or
https://blog.gospodarets.com/fetch_in_action

Related

Swift, JSON model

I have a question regarding building a JSON model namely, I should declare a date that will be different each day - in this case: "2020-11-19" as below.
This is a response for the current day.
{
"dates": {
"2020-11-19": {
"countries": {
"Poland": {
"date": "2020-11-19",
"id": "poland",
"links": [
{
"href": "/api/2020-11-19/country/poland",
"rel": "self",
"type": "GET"
}
],
"name": "Poland",
"name_es": "Polonia",
"name_it": "Polonia",
"regions": [],
"source": "John Hopkins University",
"today_confirmed": 796798,
"today_deaths": 12088,
"today_new_confirmed": 23975,
"today_new_deaths": 637,
"today_new_open_cases": 4335,
"today_new_recovered": 19003,
"today_open_cases": 422824,
"today_recovered": 361886,
"today_vs_yesterday_confirmed": 0.03102262743215456,
"today_vs_yesterday_deaths": 0.05562832940354556,
"today_vs_yesterday_open_cases": 0.010358695210626712,
"today_vs_yesterday_recovered": 0.055421236981710864,
"yesterday_confirmed": 772823,
"yesterday_deaths": 11451,
"yesterday_open_cases": 418489,
"yesterday_recovered": 342883
}
},
"info": {
"date": "2020-11-19 00:00CET",
"date_generation": "2020-11-19 22:34",
"yesterday": "2020-11-18 00:00CET"
}
}
},
"metadata": {
"by": "Narrativa & AppliedXL",
"url": [
"wwww.narrativa.com",
"www.appliedxl.com"
]
},
"total": {
"date": "2020-11-19",
"name": "Total",
"name_es": "Total",
"name_it": "Total",
"rid": "#total",
"source": "Narrativa",
"today_confirmed": 56684618,
"today_deaths": 1356365,
"today_new_confirmed": 525111,
"today_new_deaths": 8186,
"today_new_open_cases": 273944,
"today_new_recovered": 242981,
"today_open_cases": 19082735,
"today_recovered": 36245518,
"today_vs_yesterday_confirmed": 0.009350349175964112,
"today_vs_yesterday_deaths": 0.00607189401407382,
"today_vs_yesterday_open_cases": 0.014564678824917632,
"today_vs_yesterday_recovered": 0.00674899660543371,
"yesterday_confirmed": 56159507,
"yesterday_deaths": 1348179,
"yesterday_open_cases": 18808791,
"yesterday_recovered": 36002537
},
"updated_at": "2020-11-19 21:34UTC"
}
How I should build a model so that this property would be changed every day? (of course, this date needs to have a proper format "yyyy-MM-dd")
I would probably do:
var dates: [String: YourModel]
if it will potentially have multiple dates in that field.. otherwise, I'd probably do a custom object that overrides init(from decoder: and parses out that info

foursquare venue result locale

https://developer.foursquare.com/overview/versioning it says:
You can specify the locale by setting the Accept-Language HTTP header in your request. Alternatively, you can add a locale=XXX parameter to your request but HTTP header specification is preferred. We currently support en (default), es, fr, de, it, ja, th, tr, ko, ru, pt, and id.
and
If nothing is specified, for geographical entities (e.g., city names), we'll fall back to using the language that's most popular in the country for that venue.
Now, how do we get the locale of the API result? If I query with tr locale, it may answer me back with en or another fallback locale. I couldn't find it neither inside the results nor the response headers.
I need this to cache and show the users the right data. My website's fallback language is en for example, but the API might give me de for example.
Thanks.
Edit Here's an example of what I try to tell;
URL:
https://api.foursquare.com/v2/venues/4adcda50f964a520354121e3
?client_id=[client_id]&client_secret=[client_secret]&v=20161115&locale=tr
Headers:
array (
'Accept-Language' => 'tr',
'Accept' => 'application/json'
)
Result (Cropped some unrelated items):
{
"meta": {
"code": 200,
"requestId": "582bfe9e1ed21964a18d3aab"
},
"response": {
"venue": {
"id": "4adcda50f964a520354121e3",
"name": "La Pedrera (Casa Milà) (Casa Milà 'La Pedrera')",
"contact": {
"phone": "+34902202138",
"formattedPhone": "+34 902 20 21 38",
"twitter": "catfundacio",
"facebook": "429182007214758",
"facebookUsername": "lapedrera.barcelona",
"facebookName": "La Pedrera-Casa Milà"
},
"location": {
"address": "Pg. Gràcia, 92",
"crossStreet": "Carrer Provença",
"lat": 41.39509128050475,
"lng": 2.1618343621091296,
"postalCode": "08008",
"cc": "ES",
"city": "Barselona",
"state": "Cataluña",
"country": "İspanya",
"formattedAddress": [
"Pg. Gràcia, 92 (Carrer Provença)",
"08008 Barselona Catalonia",
"İspanya"
]
},
"canonicalUrl": "https:\/\/foursquare.com\/v\/la-pedrera-casa-mil%C3%A0\/4adcda50f964a520354121e3",
"categories": [
{
"id": "4bf58dd8d48988d12d941735",
"name": "Anıt \/ Abide",
"pluralName": "Anıtlar \/ Abideler",
"shortName": "Abide",
"icon": {
"prefix": "https:\/\/ss3.4sqi.net\/img\/categories_v2\/building\/government_monument_",
"suffix": ".png"
},
"primary": true
},
{
"id": "4bf58dd8d48988d130941735",
"name": "Bina",
"pluralName": "Binalar",
"shortName": "Bina",
"icon": {
"prefix": "https:\/\/ss3.4sqi.net\/img\/categories_v2\/building\/default_",
"suffix": ".png"
}
}
],
"description": "La Pedrera (Casa Milà) és un edifici construït per Antoni Gaudí i declarat Patrimoni de la Humanitat. Actualment és la seu de la Fundació Catalunya-La Pedrera.",
"storeId": "",
"tags": [
"gallery",
"gaudi",
"modernisme",
"museum",
"photobooth",
"sicted"
],
"shortUrl": "http:\/\/4sq.com\/72NCMi",
"timeZone": "Europe\/Madrid",
"hours": {
"status": "09:00'e kadar kapalı",
"isOpen": false,
"isLocalHoliday": false,
"timeframes": [
{
"days": "Pzt\u2013Paz",
"includesToday": true,
"open": [
{
"renderedTime": "09:00\u201321:00"
}
],
"segments": [
]
}
]
},
"attributes": {
"groups": [
{
"type": "wifi",
"name": "Kablosuz Bağlantı",
"summary": "Ücretsiz Wi-Fi",
"count": 1,
"items": [
{
"displayName": "Kablosuz Bağlantı",
"displayValue": "Ücretsiz"
}
]
}
]
},
"bestPhoto": {
"id": "55672a92498ec352981dd144",
"createdAt": 1432824466,
"source": {
"name": "Foursquare Web",
"url": "https:\/\/foursquare.com"
},
"prefix": "https:\/\/irs2.4sqi.net\/img\/general\/",
"suffix": "\/39082263_M0PK-NTv3A-0tI4j_aEIp5k6BEkliQTkMXS9TIPg_NQ.jpg",
"width": 620,
"height": 478,
"visibility": "public"
}
}
}
}
The addresses, categories, some of the names, timeframes, attributes sections are in fact Turkish, but the description and the most of the names are in fallback/local language which is Spanish in this case.
The locale is not specified in the API response.
If you don't specify anything in the Accept-Language HTTP header the response will default to the language that's most popular in the country. However, if you do specify a local the API won't fallback to anything else.
If your website's language is english, you can specify en in the Accept-Language HTTP header and the API will give you english too.

Serialize the response from backend to store ember store

My response from backend is not in form which ember store. I am not able to serialize the response.
response.json
[{
"pk": 127,
"url": "http://example.com/api/galleries/127/",
"gallery_name": "Faces",
"thumbnail_url": "https://example.cloud.net/galleryThumbs/2656a05c-4ec7-3eea-8c5e-d8019454d443.jpg",
"time": "1 month ago",
"description": "Created by user",
"is_following": true,
"feedPhotos": [{
"pk": 624,
"url": "http://example.com/api/photos/624/",
"profilePic": "https://example.cloud.net/userDPs/50906ce2-394d-39c8-9261-8cf78e3611c2.jpg",
"userName": "Nabeela",
"userKarma": 915,
"caption": "Old woman spinning her 'chhos-khor' ...a rotation of which is equivalent to the recitation of a mantra.",
"numComments": 0,
"owner": "http://example.com/api/users/44/",
"time": "1 month ago",
"photo_url": "https://example.cloud.net/photos/9cbd6423-3bc5-36e0-b8b4-d725efb3249a.jpg",
"comments_url": "http://example.com/api/photos/624/comments/",
"numFives": 4,
"fivers_url": "http://example.com/api/photogalleries/1362/fivers/",
"fivers_pk": 1362,
"fullphoto_url": "http://example.com/api/photogalleries/1362/photo/",
"fullphoto_pk": 1362,
"is_fived": true,
"hiFiveKarma": 1,
"owner_pk": 44,
"userFirstName": "Nabeela",
"is_bookmarked": false
}, {
"pk": 574,
"url": "http://example.com/api/photos/574/",
"profilePic": "https://example.cloud.net/userDPs/b6f69e4e-980d-3cc3-8b3e-3eb1a7f21350.jpg",
"userName": "Rohini",
"userKarma": 194,
"caption": "Life # Myanmar!",
"numComments": 0,
"owner": "http://example.com/api/users/45/",
"time": "2 months ago",
"photo_url": "https://example.cloud.net/photos/eeae72d5-d6af-391e-a218-b442c0c7e34e.jpg",
"comments_url": "http://example.com/api/photos/574/comments/",
"numFives": 2,
"fivers_url": "http://example.com/api/photogalleries/1303/fivers/",
"fivers_pk": 1303,
"fullphoto_url": "http://example.com/api/photogalleries/1303/photo/",
"fullphoto_pk": 1303,
"is_fived": false,
"hiFiveKarma": 0,
"owner_pk": 45,
"userFirstName": "Rohini",
"is_bookmarked": false
}
]
}, {
"pk": 65,
"url": "http://example.com/api/galleries/65/",
"gallery_name": "Royal",
"thumbnail_url": "https://example.cloud.net/galleryThumbs/d8a900af-1f1d-3977-8cc8-b8bb36e32be5.jpg",
"time": "2 months ago",
"description": "This is a gallery about Royal",
"is_following": false,
"feedPhotos": [{
"pk": 347,
"url": "http://example.com/api/photos/347/",
"profilePic": "https://example.cloud.net/userDPs/50906ce2-394d-39c8-9261-8cf78e3611c2.jpg",
"userName": "Nabeela",
"userKarma": 915,
"caption": "I cannot forget the name of this palace - Moti Mahal (translation: Pearl Palace). Indescribably beautiful, ainnit! at Mehrangarh fort, Jodhp",
"numComments": 0,
"owner": "http://example.com/api/users/44/",
"time": "2 months ago",
"photo_url": "https://example.cloud.net/photos/958ed406-708e-3f01-a2f4-9467cd709fdd.jpg",
"comments_url": "http://example.com/api/photos/347/comments/",
"numFives": 4,
"fivers_url": "http://example.com/api/photogalleries/759/fivers/",
"fivers_pk": 759,
"fullphoto_url": "http://example.com/api/photogalleries/759/photo/",
"fullphoto_pk": 759,
"is_fived": false,
"hiFiveKarma": 0,
"owner_pk": 44,
"userFirstName": "Nabeela",
"is_bookmarked": false
}, {
"pk": 593,
"url": "http://example.com/api/photos/593/",
"profilePic": "https://example.cloud.net/userDPs/95ac6974-f7df-338c-ab84-99fa1df7514c.jpg",
"userName": "Vikanshu",
"userKarma": 932,
"caption": "Marvelous architecture!! in Florence, Italy",
"numComments": 0,
"owner": "http://example.com/api/users/48/",
"time": "1 month ago",
"photo_url": "https://example.cloud.net/photos/7a86eb37-6c68-3d6c-b6cf-2e3b74d330dd.jpg",
"comments_url": "http://example.com/api/photos/593/comments/",
"numFives": 4,
"fivers_url": "http://example.com/api/photogalleries/1363/fivers/",
"fivers_pk": 1363,
"fullphoto_url": "http://example.com/api/photogalleries/1363/photo/",
"fullphoto_pk": 1363,
"is_fived": false,
"hiFiveKarma": 0,
"owner_pk": 48,
"userFirstName": "Vikanshu",
"is_bookmarked": false
}]
}]
How do I serialize this using JSONPISerailizer or any other serializer in ember-cli so that it gets stored in ember store
Reference jsonapi.org
++++Top Level:
Root:
A JSON object must be root of every JSON API request response.
A document must contain at least one top-level members:
1. data: documents "primary data"
2. errors: an array of error objects (id,status,code,title....)
3. meta: a meta object that contains non-standard meta-information (copyright,author...)
member data and errors must not co-exist together.
"data"{}
+++++Resource Objects
1. A resource object MUST contain atleast following top-level member
*id
*type
```
//structure-1
//for galleries
{
"data": {
"type": "galleries",
"id": "1"
}
}
//for photos
{
"data": {
"type": "photos",
"id": "1"
}
}
```
In addition, a resource object may contain any of these top-level members
*attributes
*relationship
*links
*meta
//added attributes first
```
//structure-2
//for galleries
{
"data": {
"type": "galleries",
"id": "1",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
}
}
}
//for photos
{
"data": {
"type": "photos",
"id": "1",
"attributes":{
userName: "Nabeela",
userKarma: 915
}
}
}
```
//Adding relationship
Relationship object must contain atleast one of the following
*links (containing atleast one of "self" or "related" resource link
*data
*meta
//link in relationship (minimum one required from link,data,meta).
//
```
//structure-3
//for galleries
{
"data":[{ //Array(square bracket as adding relationship one more item to data
"type": "galleries",
"id": "1",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
},
"relationships":{
"links":{
"self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
},
}]
}
}
```
//data in relationship
```
//structure-4
//for galleries
{
"data": [{
"type": "galleries",
"id": "1",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
},
"relationships":{ //This has all your photo stuff
"links":{
"self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
},
"data": { //picked it up from structure-1
"type": "photos",
"id": "77"
}
}]
}
}
```
//Adding related resource "included"
```
//for galleries
{
"data": [{
"type": "galleries",
"id": "1",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
},
"relationships":{ //This has all your photo stuff
"links":{
"self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
},
"data": { //picked it up from structure-1
"type": "photos",
"id": "77"
}
}],
"included":[{
"type": "photos",
"id": "77",
"attributes":{
userName: "Nabeela",
userKarma: 915
},
{
"type": "photos",
"id": "78",
"attributes":{
userName: "Nabeela",
userKarma: 915
}
}]
}
}
```
For collections. I am not confident but try this
Now for collection of galleries.
//for galleries
{
"data": [{
"type": "galleries",
"id": "1",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
},
"relationships":{ //This has all your photo stuff
"links":{
"self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
},
"data": { //picked it up from structure-1
"type": "photos",
"id": "77"
}
},{
"type": "galleries",
"id": "2",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
},
"relationships":{ //This has all your photo stuff
"links":{
"self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
},
"data": { //picked it up from structure-1
"type": "photos",
"id": "79"
}
}],
"included":[{
"type": "photos",
"id": "77",
"attributes":{
userName: "Nabeela",
userKarma: 915
},{
"type": "photos",
"id": "78",
"attributes":{
userName: "Nabeela",
userKarma: 915
},{
"type": "photos",
"id": "79",
"attributes":{
userName: "Nabeela",
userKarma: 915
}
}]
}
}
============Implementation part =================================
JSONSerializer normalization process follows these steps
*normalizeResponse : entry method.
*normalizeCreateRecordResponse : a normalizeResponse for specific operation.
*normalizeSingleResponse|normalizeArrayResponse:
- for methods like createRecord. we expect a single record back.
- for methods like findAll we expect multiple records back.
+normalize =
normalizeArray iterates and calls normalize for each of it's records
normalizeSingle call its once.
+extractID | extractAttributes | extractRelationships
= normalize delegates to these method to turn record payload into jsonAPI format
Starting with normalizeResponse method. If you open and see normalizeResponse method
in json-serializer
link normalizeResponse: https://github.com/emberjs/data/blob/v2.2.1/packages/ember-
data/lib/serializers/json-serializer.js#L192
you with find a switch case switch(requestType). If requestType if
"findRecord" then "normalizeFindRecordResponse" is called
"queryRecord" then "normalizeQueryRecordResponse" is called
"findAll" then "normalizeFindAllResponse" is called
...so on and so forth.
if you notice the parameter passed to all the methods are same as that of normalize
(...arguments) :)
**Lets start for findAll
i.e normalizeResponse -> normalizeFindAllResponse -> normalizeArrayResponse
as normalizeFindAllResponse method has only one line that call
normalizeArrayResponse.
normalizeFindAllResponse
normalizeResponse -> normalizeFindAllResponse -> normalizeArrayResponse ->
_normalizeResponse{ extractMeta,normalize }
extractMeta [extract meta information like pagination and stuff ]
if single: normalize []
example of normalize method in emberjs docs
```
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
normalize: function(typeClass, hash) {
var fields = Ember.get(typeClass, 'fields');
fields.forEach(function(field) {
var payloadField = Ember.String.underscore(field);
if (field === payloadField) { return; }
hash[field] = hash[payloadField];
delete hash[payloadField];
});
return this._super.apply(this, arguments);
}
});
```
"normalizeArrayResponse calls `return this._normalizeResponse
(store,primaryModelClass,payload,id,requestType,false).
so isSingle is false for _normalizeResponse method. so we will have to push all the
related records of included array
in our case the photos which is done by below snippet from "_normalizeRespose"
method.
_normalizeResponse
```
else{
documentHash.data = payload.map((item) => {
let { data, included } = this.normalize(primaryModelClass,item);
if(included){
documentHash.included.push(...included);
}
return data;
});
return documentHash;
}
```
Things are still unclear in the context of our JSON reponse from server
but atleast we know the flow now.
Lets try to apply it for findAll ( as per the flow above).
run "ember g serializer application" //assuming you are using ember-cli and you
intend to make this serializer generic for application.
As of now I have no information how and when normalizeResponse is called. :(
I just scanned through and guess on recieving data from server the store calls
normalizeResponseHelpers which in turn calls normalizeResponse.
In any case "normalizeResponse" is going to send payload and other necessar
information to normalizeFindAllResponse(...arguments) which in turn will call
normalizeArrayResponse(...arguments) which in turn will call "_normalizeRespone".
Here is where we need to take action
for extraMeta and normalize.
+extraMeta
I am not sure if there is any meta information in you json response.
in case there is you can refer to the example mentioned in docs
extractMeta
So I guess you can directly user the normalize method from example in your application ;).
please try and check. Since i am learning ember myself I cannot guarantee it will work but it should. the lonngggg explation is my thought while i was learning the problem/solution
//app/serializers/application.js
+normalize
```
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
normalize: function(typeClass, hash) {
var fields = Ember.get(typeClass, 'fields');
fields.forEach(function(field) {
var payloadField = Ember.String.underscore(field);
if (field === payloadField) { return; }
hash[field] = hash[payloadField];
delete hash[payloadField];
});
return this._super.apply(this, arguments);
}
});
```
The primary key in the JSON from server is pk. You will have to mention that too
http://emberjs.com/api/data/classes/DS.JSONSerializer.html#property_primaryKey
app/serializers/application.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
primaryKey: 'pk'
});

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.

creating JSON object without using a list

I want to be able to create a JSON object so that I can access it like this.
education.schools.UNCC.graduation
Currently, my JSON is like this:
var education = {
"schools": [
"UNCC": {
"graduation": 2015,
"city": "Charlotte, NC",
"major": ["CS", "Spanish"]
},
"UNC-CH": {
"graduation": 2012,
"city": "Chapel Hill, NC"
"major": ["Sociology", "Film"]
}
],
"online": {
"website": "Udacity",
"courses": ["python", "java", "data science"]
}
};
When I go to Lint my JSON, I get an error message.
I know I can reformat my object to access it like this (below), but I don't want to do it this way. I want to be able to call the school name, and not use an index number.
education.schools[1].graduation
Objects have named keys. Arrays are a list of members.
Replace the value of "schools" with an object. Change [] to {}.
This is your JSON corrected.
Your JSON is invalid.
{
"schools": [
{
"UNCC": {
"graduation": "2015",
"city": [
"CS",
"Spanish"
],
"major": [
"CS",
"Spanish"
]
}
},
{
"UNC-CH": {
"graduation": "2012",
"city": [
"Chapel Hill",
"NC"
],
"major": [
"Sociology",
"Film"
]
}
}
],
"online": {
"website": "Udacity",
"courses": [
"python",
"java",
"data science"
]
}
}
Explanation:
"city": "Chapel Hill, NC" -> this is a array with 2 values "Chapel Hill" and "HC", like you do with major and courses.
The Schools array, you need to use this sintaxe to construct a array [{
http://adobe.github.io/Spry/samples/data_region/JSONDataSetSample.html