Trouble getting data from JSON with ReactJS - javascript

I have a JSON file like this, named data.json
{
"link_template": "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?limit={num-results}&country={country-code}",
"links": {
"alternate": "http://www.rottentomatoes.com/movie/box-office/",
"self": "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?limit=20&country=us"
},
"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
},
{
"abridged_cast": [
{
"characters": [
"Oh"
],
"id": "770702500",
"name": "Jim Parsons"
},
{
"characters": [
"Tip"
],
"id": "351524959",
"name": "Rihanna"
},
{
"characters": [
"Captain Smek"
],
"id": "162654836",
"name": "Steve Martin"
},
{
"id": "162652167",
"name": "Jennifer Lopez"
}
],
"alternate_ids": {
"imdb": "2224026"
},
"critics_consensus": "",
"id": "771315639",
"links": {
"alternate": "http://www.rottentomatoes.com/m/home_2015/",
"cast": "http://api.rottentomatoes.com/api/public/v1.0/movies/771315639/cast.json",
"reviews": "http://api.rottentomatoes.com/api/public/v1.0/movies/771315639/reviews.json",
"self": "http://api.rottentomatoes.com/api/public/v1.0/movies/771315639.json",
"similar": "http://api.rottentomatoes.com/api/public/v1.0/movies/771315639/similar.json"
},
"mpaa_rating": "PG",
"posters": {
"detailed": "http://resizing.flixster.com/LO7V_j1xUTlsbwzIyCINBxBm5qE=/54x80/dkpu1ddg7pbsk.cloudfront.net/movie/11/18/17/11181778_ori.jpg",
"original": "http://resizing.flixster.com/LO7V_j1xUTlsbwzIyCINBxBm5qE=/54x80/dkpu1ddg7pbsk.cloudfront.net/movie/11/18/17/11181778_ori.jpg",
"profile": "http://resizing.flixster.com/LO7V_j1xUTlsbwzIyCINBxBm5qE=/54x80/dkpu1ddg7pbsk.cloudfront.net/movie/11/18/17/11181778_ori.jpg",
"thumbnail": "http://resizing.flixster.com/LO7V_j1xUTlsbwzIyCINBxBm5qE=/54x80/dkpu1ddg7pbsk.cloudfront.net/movie/11/18/17/11181778_ori.jpg"
},
"ratings": {
"audience_rating": "Upright",
"audience_score": 69,
"critics_rating": "Rotten",
"critics_score": 47
},
"release_dates": {
"theater": "2015-03-26"
},
"runtime": 93,
"synopsis": "When Oh, a loveable misfit from another planet, lands on Earth and finds himself on the run from his own people, he forms an unlikely friendship with an adventurous girl named Tip who is on a quest of her own. Through a series of comic adventures with Tip, Oh comes to understand that being different and making mistakes is all part of being human. And while he changes her planet and she changes his world, they discover the true meaning of the word HOME. (c) Fox",
"title": "Home",
"year": 2015
}
]
}
This is my ReactJS code, intended to get data from that JSON file and bind in my React components
var CastMember=React.createClass({
render:function(){
<div className="castmember">
</div>
}
});
var Cast=React.createClass({
render:function(){
var cast_members=this.props.cast.map(function (member){
return (
<CastMember member={member}/>
);
});
return (
<div className="cast">
{cast_members}
</div>
);
}
});
var Movie=React.createClass({
render:function(){
return (
<div className="movieBox">
<Cast cast={this.props.movie.abridged_cast}/>
</div>
);
}
});
var MovieList=React.createClass({
render:function(){
var movieNodes=this.props.movies.map(function (movie){
return (
<Movie movie={movie}/>
);
});
return (
<div className="movieList">
{movieNodes}
</div>
);
}
});
var DataBlock = React.createClass({
getInitialState:function() {
return {data:{
movies:[
{abridged_cast:[]}
]
}}
},
componentDidMount:function() {
var a=this;
$.ajax({
url:this.props.url,
dataType:'json',
cache:false,
success:function(data){
this.setState({data:data})
}.bind(this)
});
},
render: function() {
return (
<div className="dataBlock">
<h1>Movie List</h1>
<MovieList movies={this.state.data.movies}/>
</div>
);
}
});
React.render(
<DataBlock url="data.json"/>,
document.getElementById('content')
);
I have been doing this demo in bottom-to-top order. I was able to get list of movies from JSON file and render it, but now stuck in getting abridged_cast in each movie
In render function of Cast component, if I replace it with rendering {this.props.cast}, everything will show up. But I fail in mapping them to member property of CastMember component: My code above didn't display anything. What's wrong with my code?

var CastMember=React.createClass({
render:function(){
<div className="castmember">
</div>
}
});
CastMember component should handle its prop, as you pass the data member to CastMember-> <CastMember member={member}/>.
This would be help:
var CastMember=React.createClass({
render:function(){
return (
<div className="castmember">
{this.props.member}
</div>
);
}
});

Related

I am using Jest to run some test in React. But when I run the test I receive the error " Cannot read property 'dateTime' of undefined

I have multiple test in my file but I will use the first one as an example.
import React from 'react';
import { shallow } from 'enzyme';
import Event from '../Event';
import { mockData } from '../mock-data';
describe('<Event /> component', () => {
let EventWrapper;
beforeAll(() => {
EventWrapper = shallow(<Event event={mockData} />)
})
test('rendered event container', () => {
expect(EventWrapper.find('.event-container')).toHaveLength(1);
});
})
Then here is my React Component file
import React, { Component } from 'react';
class Event extends Component {
state = {
showingDetails: false
}
eventDetails = () => {
const showingDetails = this.state.showingDetails;
if (showingDetails === false) {
this.setState({
showingDetails: true
})
} else {
this.setState({
showingDetails: false
})
}
};
render() {
const { event } = this.props;
const eventISODateTime = new Date(event.start.dateTime);
const eventDate = eventISODateTime.toDateString();
const eventTime = eventISODateTime.toTimeString();
const eventTimeFormatted = `${eventTime.slice(0, 5)} ${eventTime.slice(18)}`;
return <div className="event-container">
<h1 className="event-summary">{event.summary}</h1>
<p className="event-date">{eventDate} </p>
<p className="event-time">{eventTimeFormatted}</p>
<p className="event-location">{event.location}</p>
{this.state.showingDetails && (
<div className="event-details">
<h3 className="about-event">About event:</h3>
<a className="details-link" target="_blank" rel="noreferrer" href={event.htmlLink}>See details on Google Calendar</a>
<p className="event-description">{event.description}</p>
</div>
)}
<button className="show-hide" onClick={() => this.eventDetails()}> {this.state.showingDetails ? 'hide description' : 'show description'} </button>
</div >
}
}
export default Event;
I defined dateTime inside of the render().
I using the same { mockData } for each file . When I load my site either in localhost or on Github gh-pages it works fine and displays the data correctly, so it is just giving me an error when running the test 'npm run test'
Here is the mockData file I am pulling from
const mockData = [
{
"kind": "calendar#event",
"etag": "\"3181161784712000\"",
"id": "4eahs9ghkhrvkld72hogu9ph3e_20200519T140000Z",
"status": "confirmed",
"htmlLink": "https://www.google.com/calendar/event?eid=NGVhaHM5Z2hraHJ2a2xkNzJob2d1OXBoM2VfMjAyMDA1MTlUMTQwMDAwWiBmdWxsc3RhY2t3ZWJkZXZAY2FyZWVyZm91bmRyeS5jb20",
"created": "2020-05-19T19:17:46.000Z",
"updated": "2020-05-27T12:01:32.356Z",
"summary": "Learn JavaScript",
"description": "Have you wondered how you can ask Google to show you the list of the top ten must-see places in London? And how Google presents you the list? How can you submit the details of an application? Well, JavaScript is doing these. :) \n\nJavascript offers interactivity to a dull, static website. Come, learn JavaScript with us and make those beautiful websites.",
"location": "London, UK",
"creator": {
"email": "fullstackwebdev#careerfoundry.com",
"self": true
},
"organizer": {
"email": "fullstackwebdev#careerfoundry.com",
"self": true
},
"start": {
"dateTime": "2020-05-19T16:00:00+02:00",
"timeZone": "Europe/Berlin"
},
"end": {
"dateTime": "2020-05-19T17:00:00+02:00",
"timeZone": "Europe/Berlin"
},
"recurringEventId": "4eahs9ghkhrvkld72hogu9ph3e",
"originalStartTime": {
"dateTime": "2020-05-19T16:00:00+02:00",
"timeZone": "Europe/Berlin"
},
"iCalUID": "4eahs9ghkhrvkld72hogu9ph3e#google.com",
"sequence": 0,
"reminders": {
"useDefault": true
},
"eventType": "default"
},
{
"kind": "calendar#event",
"etag": "\"3181159875584000\"",
"id": "3qtd6uscq4tsi6gc7nmmtpqlct_20200520T120000Z",
"status": "confirmed",
"htmlLink": "https://www.google.com/calendar/event?eid=M3F0ZDZ1c2NxNHRzaTZnYzdubW10cHFsY3RfMjAyMDA1MjBUMTIwMDAwWiBmdWxsc3RhY2t3ZWJkZXZAY2FyZWVyZm91bmRyeS5jb20",
"created": "2020-05-19T19:14:30.000Z",
"updated": "2020-05-27T11:45:37.792Z",
"summary": "React is Fun",
"description": "Love HTML, CSS, and JS? Want to become a cool front-end developer? \n\nReact is one of the most popular front-end frameworks. There is a huge number of job openings for React developers in most cities. \n\nJoin us in our free React training sessions and give your career a new direction. ",
"location": "Berlin, Germany",
"creator": {
"email": "fullstackwebdev#careerfoundry.com",
"self": true
},
"organizer": {
"email": "fullstackwebdev#careerfoundry.com",
"self": true
},
"start": {
"dateTime": "2020-05-20T14:00:00+02:00",
"timeZone": "Europe/Berlin"
},
"end": {
"dateTime": "2020-05-20T15:00:00+02:00",
"timeZone": "Europe/Berlin"
},
"recurringEventId": "3qtd6uscq4tsi6gc7nmmtpqlct",
"originalStartTime": {
"dateTime": "2020-05-20T14:00:00+02:00",
"timeZone": "Europe/Berlin"
},
"iCalUID": "3qtd6uscq4tsi6gc7nmmtpqlct#google.com",
"sequence": 0,
"reminders": {
"useDefault": true
},
"eventType": "default"
},
{
"kind": "calendar#event",
"etag": "\"3181161784712000\"",
"id": "4eahs9ghkhrvkld72hogu9ph3e_20200521T140000Z",
"status": "confirmed",
"htmlLink": "https://www.google.com/calendar/event?eid=NGVhaHM5Z2hraHJ2a2xkNzJob2d1OXBoM2VfMjAyMDA1MjFUMTQwMDAwWiBmdWxsc3RhY2t3ZWJkZXZAY2FyZWVyZm91bmRyeS5jb20",
"created": "2020-05-19T19:17:46.000Z",
"updated": "2020-05-27T12:01:32.356Z",
"summary": "Learn JavaScript",
"description": "Have you wondered how you can ask Google to show you the list of the top ten must-see places in London? And how Google presents you the list? How can you submit the details of an application? Well, JavaScript is doing these. :) \n\nJavascript offers interactivity to a dull, static website. Come, learn JavaScript with us and make those beautiful websites.",
"location": "London, UK",
"creator": {
"email": "fullstackwebdev#careerfoundry.com",
"self": true
},
"organizer": {
"email": "fullstackwebdev#careerfoundry.com",
"self": true
},
"start": {
"dateTime": "2020-05-21T16:00:00+02:00",
"timeZone": "Europe/Berlin"
},
"end": {
"dateTime": "2020-05-21T17:00:00+02:00",
"timeZone": "Europe/Berlin"
},
"recurringEventId": "4eahs9ghkhrvkld72hogu9ph3e",
"originalStartTime": {
"dateTime": "2020-05-21T16:00:00+02:00",
"timeZone": "Europe/Berlin"
},
"iCalUID": "4eahs9ghkhrvkld72hogu9ph3e#google.com",
"sequence": 0,
"reminders": {
"useDefault": true
},
"eventType": "default"
},
];
export { mockData };

Access data / Structure data in ReactJS / Firebase

I'm a little bit losted coming from Rails to React/Firebase. I have the following realtime database structure. As you can see, a product can have a brand and multiple sellers.
If a brand is true, i'd like to get / display the brand contents on my page (the avatar, name, link etc.). Same for the sellers.
Right now, if i try to display the brand content, i get "true" when i'd like an object containing the infos i've stored in brands or sellers.
So i'd like for example to be able to do something like this :
<p>{this.props.brands.name}</p> (it can only have one brand for now)
As for the sellers i'd like for example to be able to do something like this :
this.state.sellers.map((seller) =>
<div>
<img src={seller.avatar} />
<p>{seller.name}</p>
</div>
);
Here is my firebase realtime database structure (json) :
{
"products": {
"1": {
"name": "Nike HyperAdapt 1.0",
"tagline": "Self-lacing running shoes",
"releaseDate": "20.08.2020",
"brands": {
"Nike": true
},
"thumbnail": "/img/thumbnails/nike-hyperadapt-thumbnail.jpg",
"media": "/img/media/nike-hyperadapt-media-01.jpeg",
"isRaffle": true,
"description": "Nike HyperAdapt 1.0 is Nike's first line of shoes that can lace themselves, thanks to an internal cable system comprised of fishing line and a pressure sensor located in the sole that responds to the weight of your foot as you move with an algorithmic pressure equation.",
"upvote": "169",
"sellers": {
"Shop 01": true,
"Nike": true
}
},
"2": {
"name": "Puma Fi",
"tagline": "Self lacing shoes by Puma",
"releaseDate": "22.08.2020",
"brands": {
"Puma": true
},
"thumbnail": "/img/thumbnails/puma-fi-thumbnail.jpg",
"media": "/img/media/puma-fi-media-01.jpeg",
"isRaffle": true,
"description": "The technology platform Fit Intelligence (Fi) is designed to automate and finetune performance for our footwear. The very first Fi footwear style is a self-lacing training shoe made for workouts and light running.",
"upvote": "88",
"sellers": {
"Shop 01": true,
"Puma": true
}
}
},
"brands": {
"Nike": {
"name": "Nike",
"avatar": "/img/brands/nike-logo.png",
"link": "https://www.nike.com/fr",
"products": {
"1": true
}
},
"Puma": {
"name": "Puma",
"avatar": "/img/brands/puma-logo.png",
"link": "https://eu.puma.com/fr/fr/home",
"products": {
"2": true
}
}
},
"sellers": {
"Shop 01": {
"name": "Shop 01",
"avatar": "/img/sellers/shop-01-logo.png",
"link": "https://www.shop-01.com/",
"products": {
"1": true,
"2": true
}
},
"Nike": {
"name": "Nike",
"avatar": "/img/sellers/nike-store-logo.png",
"link": "https://www.nike.com/fr/launch",
"products": {
"1": true
}
},
"Puma": {
"name": "Puma",
"avatar": "/img/sellers/puma-logo.png",
"link": "https://eu.puma.com/fr/fr/home",
"products": {
"2": true
}
}
}
}
EDIT :
here is what the component that's supposed to show the data looks like :
import React, { Component } from 'react';
import ProductPopup from './ProductPopup';
class ProductItem extends Component {
constructor() {
super();
this.state = {
productPopupStatus: false,
};
}
showProductPopup = () => {
this.setState({ productPopupStatus: true });
};
hideProductPopup = () => {
this.setState({ productPopupStatus: false });
};
renderUpvoteBtn() {
return (
<div className="upvote-btn_wrapper">
<a className="upvote-btn" href="#">
<span className="upvote-counter">
<i className="fas fa-sort-up"></i>
<span>{this.props.upvote}</span>
</span>
</a>
</div>
);
}
renderInfoSession() {
return (
<section className="product-item-info">
<span>
<h2>{this.props.name}</h2>
</span>
<p>{this.props.tagline}</p>
<div className="product-item_meta-shadow"></div>
</section>
);
}
renderMeta() {
return (
<div className="product-item_meta">
<a href="#">
// SHOW ASSOCIATED BRAND AVATAR AND NAME
</a>
</div>
);
}
render() {
return (
<li className="product-item">
{this.renderUpvoteBtn()}
<a href="#" onClick={this.showProductPopup} className="product-item_content">
<img className="product-item-media" src={this.props.media} />
{this.renderInfoSession()}
</a>
{this.renderMeta()}
<ProductPopup status={this.state.productPopupStatus} hidePopup={this.hideProductPopup} />
</li>
);
}
}
export default ProductItem;
It seems like you're getting "true" because your brand name is a boolean. I think it might help by having your brand listed like:
brand: {
name: "Nike"
}
As far as your sellers, I feel that listing them in an array rather than an object would be better as well. You'll only be getting "true" because those values are boolean.
Is there a reason you wanted "sellers" to be an object? If not I would make it an array with objects that hold the info you need.
brands: [
{name: "Brand1", img: "imgsource1"},
{name: "Brand2", img: "imgsource2"}
]

i need to convert Json to array and i'm need to read this array [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
i have this Json and i need to read one for one with array or other but i want to put these data in a div or li can you help me?
i'm trying solved my problem with php but i don't get nothing
{"meta":{"code":200,"type":"Success","message":"Success"},"data":{"id":"0a393bcdb0a9e069447040ed7a2b7f7b","tracking_number":"1Z762E1W6842003229","carrier_code":"ups","status":"delivered","created_at":"2018-12-24T18:13:03+00:00","updated_at":"2018-12-24T21:58:44+00:00","order_create_time":null,"customer_email":"","title":"","order_id":null,"comment":null,"customer_name":null,"archived":false,"original_country":"Poland","destination_country":"Germany","itemTimeLength":42,"stayTimeLength":62,"origin_info":{"ReferenceNumber":null,"ItemReceived":"2018-09-12 21:50","ItemDispatched":null,"DepartfromAirport":null,"ArrivalfromAbroad":null,"CustomsClearance":null,"DestinationArrived":null,"weblink":"http:\/\/www.ups.com\/content\/pl\/en\/contact\/index.html?WT.svl=Footer","phone":"+48-22-534-00-00","carrier_code":"ups","trackinfo":[{"Date":"2018-10-24 13:01","StatusDescription":"Were attempting to verify the package location. \/ Investigation only","Details":"ROCKFIELD,MD,20850,US","checkpoint_status":"transit"},{"Date":"2018-09-14 09:56","StatusDescription":"Delivered","Details":"DORTMUND,44145,DE","checkpoint_status":"delivered"},{"Date":"2018-09-14 07:26","StatusDescription":"Out For Delivery","Details":"Herne-Boernig,DE","checkpoint_status":"pickup"},{"Date":"2018-09-14 05:00","StatusDescription":"Arrival Scan","Details":"Herne-Boernig,DE","checkpoint_status":"transit"},{"Date":"2018-09-14 02:14","StatusDescription":"Departure Scan","Details":"Langenhagen,DE","checkpoint_status":"transit"},{"Date":"2018-09-13 16:52","StatusDescription":"Arrival Scan","Details":"Langenhagen,DE","checkpoint_status":"transit"},{"Date":"2018-09-13 04:05","StatusDescription":"Departure Scan","Details":"Dobra Strykow,PL","checkpoint_status":"transit"},{"Date":"2018-09-13 01:40","StatusDescription":"Arrival Scan","Details":"Dobra Strykow,PL","checkpoint_status":"transit"},{"Date":"2018-09-13 00:13","StatusDescription":"Departure Scan","Details":"Wolka Kosowska,PL","checkpoint_status":"transit"},{"Date":"2018-09-12 21:50","StatusDescription":"Origin Scan","Details":"Wolka Kosowska,PL","checkpoint_status":"transit","ItemNode":"ItemReceived"},{"Date":"2018-08-11 17:17","StatusDescription":"Order Processed: Ready for UPS","Details":"PL","checkpoint_status":"transit"}]},"service_code":"UPS Standard","weight":"22.00KGS","substatus":null,"lastEvent":"Were attempting to verify the package location. \/ Investigation only,ROCKFIELD,MD,20850,US,2018-10-24 13:01","lastUpdateTime":"2018-10-24 13:01"}}
i can't read anything (data,meta,dates).
i expected same output:
<div id="data">
<li>id: 0a393bcdb0a9e069447040ed7a2b7f7b</li>
<li>Tracking_number: 1Z762E1W6842003229 </li>
...
</div>
<br>
<div id="dates">
<li>Date: 2018-09-13 16:52</li>
<li>StatusDescription": :"Departure Scan" </li> ,
<li>Details": Dobra Strykow,PL </li>
<li>checkpoint_status": transit </li>
...
</div>
<hr>
<div id="dates>
other date[2];
...
</div>
<hr>
...
You can tidy up some of the HTML in the templates. But here you go:
var dataObj = {
"meta": {
"code": 200,
"type": "Success",
"message": "Success"
},
"data": {
"id": "0a393bcdb0a9e069447040ed7a2b7f7b",
"tracking_number": "1Z762E1W6842003229",
"carrier_code": "ups",
"status": "delivered",
"created_at": "2018-12-24T18:13:03+00:00",
"updated_at": "2018-12-24T21:58:44+00:00",
"order_create_time": null,
"customer_email": "",
"title": "",
"order_id": null,
"comment": null,
"customer_name": null,
"archived": false,
"original_country": "Poland",
"destination_country": "Germany",
"itemTimeLength": 42,
"stayTimeLength": 62,
"origin_info": {
"ReferenceNumber": null,
"ItemReceived": "2018-09-12 21:50",
"ItemDispatched": null,
"DepartfromAirport": null,
"ArrivalfromAbroad": null,
"CustomsClearance": null,
"DestinationArrived": null,
"weblink": "http:\/\/www.ups.com\/content\/pl\/en\/contact\/index.html?WT.svl=Footer",
"phone": "+48-22-534-00-00",
"carrier_code": "ups",
"trackinfo": [{
"Date": "2018-10-24 13:01",
"StatusDescription": "Were attempting to verify the package location. \/ Investigation only",
"Details": "ROCKFIELD,MD,20850,US",
"checkpoint_status": "transit"
}, {
"Date": "2018-09-14 09:56",
"StatusDescription": "Delivered",
"Details": "DORTMUND,44145,DE",
"checkpoint_status": "delivered"
}, {
"Date": "2018-09-14 07:26",
"StatusDescription": "Out For Delivery",
"Details": "Herne-Boernig,DE",
"checkpoint_status": "pickup"
}, {
"Date": "2018-09-14 05:00",
"StatusDescription": "Arrival Scan",
"Details": "Herne-Boernig,DE",
"checkpoint_status": "transit"
}, {
"Date": "2018-09-14 02:14",
"StatusDescription": "Departure Scan",
"Details": "Langenhagen,DE",
"checkpoint_status": "transit"
}, {
"Date": "2018-09-13 16:52",
"StatusDescription": "Arrival Scan",
"Details": "Langenhagen,DE",
"checkpoint_status": "transit"
}, {
"Date": "2018-09-13 04:05",
"StatusDescription": "Departure Scan",
"Details": "Dobra Strykow,PL",
"checkpoint_status": "transit"
}, {
"Date": "2018-09-13 01:40",
"StatusDescription": "Arrival Scan",
"Details": "Dobra Strykow,PL",
"checkpoint_status": "transit"
}, {
"Date": "2018-09-13 00:13",
"StatusDescription": "Departure Scan",
"Details": "Wolka Kosowska,PL",
"checkpoint_status": "transit"
}, {
"Date": "2018-09-12 21:50",
"StatusDescription": "Origin Scan",
"Details": "Wolka Kosowska,PL",
"checkpoint_status": "transit",
"ItemNode": "ItemReceived"
}, {
"Date": "2018-08-11 17:17",
"StatusDescription": "Order Processed: Ready for UPS",
"Details": "PL",
"checkpoint_status": "transit"
}]
},
"service_code": "UPS Standard",
"weight": "22.00KGS",
"substatus": null,
"lastEvent": "Were attempting to verify the package location. \/ Investigation only,ROCKFIELD,MD,20850,US,2018-10-24 13:01",
"lastUpdateTime": "2018-10-24 13:01"
}
};
const packagePanel = (package) => {
let newPackage = document.createElement("div");
newPackage.innerHTML = packageData(package) + packageDates(package.origin_info.trackinfo);
return newPackage;
};
const packageData = (package) => {
return `<ul><li> id: ${package.id}</li>
<li> Tracking_number: ${package.tracking_number}</li></ul>`;
};
const packageDates = (dateArr) => {
let html = '';
dateArr.forEach(date => {
html += `<ul><li> ${date.Date} </li>
<li> Status Descriuption ${date.StatusDescription} </li>
<li> Details : ${date.Details} </li>
<li> Checkpoint status : ${date.checkpoint_status} </li></ul>`;
});
return html;
};
document.addEventListener('DOMContentLoaded', function(){
console.log('prep');
document.getElementById("data").appendChild(packagePanel(dataObj.data));
});
<div id="data">
</div>

re-map json object for messaging

I'm trying to re-map twitter direct messages data into conversation for mongodb.
"events": [
{
"type": "message_create",
"id": "1023372540847312900",
"created_timestamp": "1532826001737",
"message_create": {
"target": {
"recipient_id": "605675237"
},
"sender_id": "1020464064684806146",
"source_app_id": "268278",
"message_data": {
"text": "all right mate thank you too",
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": []
}
}
}
},
{
"type": "message_create",
"id": "1023372444210524164",
"created_timestamp": "1532825978697",
"message_create": {
"target": {
"recipient_id": "1020464064684806146"
},
"sender_id": "605675237",
"message_data": {
"text": "Okay thank you mate, this is distinquish",
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": []
}
}
}
},
{
"type": "message_create",
"id": "1023372325150965765",
"created_timestamp": "1532825950311",
"message_create": {
"target": {
"recipient_id": "1020464064684806146"
},
"sender_id": "69565292",
"message_data": {
"text": "Hello strow bree how are you",
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": []
}
}
}
},
{
"type": "message_create",
"id": "1023245595790778372",
"created_timestamp": "1532795735677",
"message_create": {
"target": {
"recipient_id": "605675237"
},
"sender_id": "1020464064684806146",
"source_app_id": "268278",
"message_data": {
"text": "Once at a social gathering, Gladstone said to Disraeli",
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": []
}
}
}
},
{
"type": "message_create",
"id": "1023245133637140484",
"created_timestamp": "1532795625491",
"message_create": {
"target": {
"recipient_id": "1020464064684806146"
},
"sender_id": "605675237",
"message_data": {
"text": "On Krat's main screen appeared the holo image of a man, and several dolphins. From the man's shape, Krat could tell it was a female, probably their leader. \"...stupid creatures unworthy of the name `sophonts.' Foolish, pre-sentient upspring of errant masters. We slip away from all your armed might, laughing at your clumsiness! We slip away as we always will, you pathetic creatures. And now that we have a real head start",
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": []
}
}
}
}
],
"apps": {
"268278": {
"id": "268278",
"name": "Twitter Web Client",
"url": "http://twitter.com"
}
}
}
I'm trying to change this data into this;
[{
members: [ '605675237', '1020464064684806146' ],
messages: [
{ author: '605675237', body: 'On Krats main screen appeared the holo image of a man, and several dolphins. From the mans shape, Krat could tell it was a female, probably their leader ...stupid creatures unworthy of the name sophonts Foolish, pre-sentient upspring of errant masters. We slip away from all your armed might, laughing at your clumsiness! We slip away as we always will, you pathetic creatures. And now that we have a real head start' },
{ author: '1020464064684806146', body: 'Once at a social gathering, Gladstone said to Disraeli' }
{ author: '605675237', body: 'Okay thank you mate, this is distinquish' }
{ author: '1020464064684806146', body: 'all right mate thank you too' },
]
},
{
members: ['69565292', '1020464064684806146'],
messages: [
{ author: '69565292', body: 'Hello strow bree how are you' }
]
}]
user_id1 must be sender_id and user_id2 must be recipient_id but actually, I have to group the twitter DM Objects by sender_id and recipient_id probably.
How can I solve this problem easily any suggestion?
Maybe we can use Lodash or Underscore to solve this remapping easily.
The solution is the group the messages by the user ids, I have created a hashed from the ids to fit it into an object:
const normalized = {};
data.events.forEach(event => {
// Just of easier access
const message = event.message_create;
// Create a temp hash which identify 2 user conversation.
// The hash is just the 2 ids with a `|` separated them
const hashedUsers = [message.sender_id, message.target.recipient_id].sort().join('|');
// The end object you wanted
const normalizedMessage = {
author: message.sender_id,
body: message.message_data.text
};
// Check if we already have this 2 users conversations, create a list of their messages
if (!normalized.hasOwnProperty(hashedUsers)) {
normalized[hashedUsers] = [normalizedMessage];
} else {
normalized[hashedUsers].push(normalizedMessage);
}
});
// Now we have a normalized object, the keys are the hash we created and the values are their messages
// so we can create the object you wanted:
const output = []
Object.entries(normalized).forEach(([key, value]) => {
output.push({
members: key.split('|'),
messages: value
})
})

Json array into select box with php

I hope someone can help me with this issue I have. What I want is a select box, which is getting filled from a json file. The problem is I have a strange kind of json file which I dont know if its array or object.
Here is how it loosk like:
{
"Id": 4,
"Name": "Testing Demo",
"OpeningHours": [
{
"Name": "Monday",
"Hours": "Kl. 09:30:00 - 21:00:00"
}
],
"Address": {
"Street": "Johnson road",
"StreetNumber": "5",
"Town": "London"
},
"Phone1": "4123213414",
"Phone2": null,
"Documents": null,
"Messages": [
{
"Title": "We are on the way",
"Body": "fine",
"Created": "01-02-2014"
},
{
"Title": "Get the stuff",
"Body": "To be ready",
"Created": "01-01-2014"
}
],
"Employees": [
{
"Name": "John Hood",
"Description": "officer",
"ProfileImageUrl": "http://grfx.cstv.com/photos/schools/kty/sports/m-baskbl/auto_headshot/9265204.jpeg"
},
{
"Name": "John hood 2",
"Description": "athletic",
"ProfileImageUrl": "http://grfx.cstv.com/photos/schools/kty/sports/m-baskbl/auto_headshot/9265204.jpeg"
}
]
}
How Iam going to show values of ID and the name?
This code it doesnt work which I dont know if Iam doing it even correctly..
(function($) {
$(document).ready(function() {
$('<tr class="form-field form-required"></tr>').append(
$('<th scope="row">New field</th>')
).append(
$('<td></td>').append(
$('<select id="release-list"></select>')
).append(
$('<p>Explanation about your new field</p>')
)
).insertAfter('#wpbody-content table tr:eq(2)');
});
$.getJSON('../../cache/path.json', function(data) {
var select = $('#release-list');
$.each(data, function(key, val){
$('<option/>').attr('value', val[key]["Id"]).html('value' + val[key]["Name"]).appendTo(select);
});
});
})(jQuery);
you can convert the data from json to array using JSON.parse()
http://www.dyn-web.com/tutorials/php-js/json/parse.php
Example:
var data = '{"first":[1,2,3],"second":[4,5,6]}';
var jsonData = JSON.parse(data);
alert(jsonData.first[1]);
alert(jsonData.second);

Categories