how to load nested data from json file in react - json

i have simple json file like this:
[{
"id": "1",
"title": "How to become a best sale marketer in a month!",
"Summary": "Lorm voluptatem reecto, quos amet hic aliquid!",
"dateAdd": "May 9, 2021",
"body": "Lorem ipsum dolor sit amet",
"child": [{
"base": "Lorem ipsum dolor sit ametLorem ipsum dolor sit amet"
}]
},
{
"id": "2",
"title": "SEO trend to look for the best in 2020",
"Summary": "Lorem ipsum",
"dateAdd": "May 9, 2020",
"body": "Lorem ipsum dolor sit amet",
"child": [{
"base": "Lorem ipsum dolor sit ametLorem ipsum dolor sit amet"
}]
}]
this is my blog component that uses the json data:
import React from "react";
import { Link } from "react-router-dom";
import data from "../../layout/data.json";
const _Blog = (props: any) => {
return (
<>
<div className="col-md-8">
{data.map((postDetail, index) => {
return (
<article className="blog-post-item">
<div className="post-thumb">
<img
src="assets/images/blog/news-1.jpg"
alt=""
className="img-fluid"
/>
</div>
<div className="post-item mt-4">
<div className="post-meta">
<span className="post-date">
<i className="fa fa-calendar-alt mr-2"></i>{postDetail.dateAdd}
</span>
</div>
<h2 className="post-title">
<a href="blog-single.html">
{postDetail.title}
</a>
</h2>
<div className="post-content">
<p>
{postDetail.body}
</p>
<h5 key={index}>
<Link to={`/blog-detail/${index + 1}`}>More</Link>
</h5>
</div>
</div>
</article>
);
})}
</div>
</>
);
};
export const Blog = _Blog;
it works correctly but i want to use the data from the child object. so i thought i should use it like this:
{postDetail.child.base} but it wont load it. Im totally lost at this point. How does {postDetail.title} or {postDetail.body} work but not the child part?

you can't access postDetail.child.base probably because postDetail.child is an array.
Try accessing it like postDetail.child[0].base.
Hope that helps.. Leave a comment if your issue is different. I'll edit my response
It should've been a comment but I don't have enough reputation.

Related

Parsing a set of JSON objects with jq

A have a big block of JSON l'm trying to parse, that looks basically like
{
"order": [
"hash1",
"hash2"
],
"posts": {
"hash4": {
"id": "hash4",
"message": "lorem ipsem"
},
"hash5": {
"id": "hash5",
"message": "dolor sit amet"
},
"hash6": {
"id": "hash6",
"message": "consectetur adipiscing elit"
}
}
}
The way I've been handling this so far is to just grep for messages
$ grep 'message' jq_dat.json
"message": "lorem ipsem"
"message": "dolor sit amet"
"message": "consectetur adipiscing elit"
This works for my current purposes, but l'd like to know how to get the same effect with jq. I.e.
$ jq .posts.<something>.message < jq_dat.json
"lorem ipsem"
"dolor sit amet"
"consectetur adipiscing elit"
I've tried using [] and {} in place of something, but those both spit back compile errors.
You just have one too many dot
jq .posts[].message < jq_dat.json

How can I add a child node to an existing json file through node js?

I am using ExpressJS to write my application and jsonfile (https://www.npmjs.com/package/jsonfile) to handle json files. I have this following json file:
{
"news": [
{
"id": "1",
"title": "News 1 heading",
"description": "Lorem ipsum dolor sit amet upidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
"dateposted": "00188292929"
},
{
"id": "2",
"title": "News 2 heading",
"description": "Lorem ipsum dolor sit amet",
"dateposted": "00188292929"
}
]
}
Now, I want to add another set of news under the "news" node, so that my final json looks like this:
{
"news": [
{
"id": "1",
"title": "News 1 heading",
"description": "Lorem ipsum dolor sit amet upidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
"dateposted": "00188292929"
},
{
"id": "2",
"title": "News 2 heading",
"description": "Lorem ipsum dolor sit amet",
"dateposted": "00188292929"
},
{
"id": "3",
"title": "News 3 heading",
"description": "Lorem ipsum dolor sit amet",
"dateposted": "00188292929"
}
]
}
There is an append flag with jsonfile but it appends at the end of the file rather than under a given node. How can I append the data under and existing node? Do, I need to stringify the json, add data and JSONfy it? or there is a more direct way?
Thanks.
You can use Json PUSH to append a json object to a current node. The code would look like this:
var json={
"news": [
{
"id": "1",
"title": "News 1 heading",
"description": "Lorem ipsum dolor sit amet upidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
"dateposted": "00188292929"
},
{
"id": "2",
"title": "News 2 heading",
"description": "Lorem ipsum dolor sit amet",
"dateposted": "00188292929"
},
{
"id": "3",
"title": "News 3 heading",
"description": "Lorem ipsum dolor sit amet",
"dateposted": "00188292929"
}
]
};
json.news.push({
"id": "3",
"title": "News 3 heading",
"description": "Lorem ipsum dolor sit amet",
"dateposted": "00188292929"
});
console.log(json);
Jsonfile's append option is referring to opening a file in append mode, in this mode you can only add to the end of the file.
You will need to re-write the entire file using the normal writeFile options. Effectively overwriting the original file.
You can see in the jsonfile code on line 91 (it is a short single file node module) that it simply passes the append flag through to fs.writeFile. I'm not entirely sure when you would use this in all honesty, but I'm assuming it's if you want to maybe output a bunch of documents and then append on some json at the bottom of each.

Saving an existing JSON file in Firebase using Swift?

I have a JSON file, saved locally in my project. Now I'm curious about saving it in Firebase. I know that Firebase saves data in a NoSQL format (as a JSON). I've seen several tutorials about adding files to Firebase, (after some action, like tapping a button in an example iOS app). But is it possible to save a whole JSON file itself (not just chunks of it) in firebase, initially (not after tapping some button), and then load that file, because in my project users can't add files on their own? The app should load the data from JSON file.
I'm new to Firebase, so I have almost no experience using it. If you have any suggestions or know how to do this, I would appreciate your help.
EDITED
Well, to clarify what I am asking about. I have a project which contains a text file, which contains a JSON data. I added it to my project, initially, because I had no experience using Firebase, AWS etc. I just needed to see how the app reacts to data. In the future the data will grow significantly, so obviously I'm not going to save it inside of the project.
The problem is, I just want to save the JSON data in Firebase. And I don't know the right way to do that: by just importing the JSON or writing it from scratch (programmatically or in a console). Also, I would like to know whether it is generally a good idea or not, because this is the first time I'm using online databases, and many people say that Firebase is the best database to start from. I'm really new to all these stuff, that's why I'm asking questions like these.
EDITED_2
{
"list": {
"restaurants": [{
"id": "231311234342bn123",
"name": "Grand Royal",
"suggested": true,
"address": {
"longitude": "30.31527",
"latitude": "59.93688",
"formatted": ["Nevskiy prospekt 10, Saint Petersburg",
"Russian Federation"
]
},
"tags": ["fish",
"Italian",
"Friends"
],
"category": "$$$$",
"description": "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda.",
"shortDescription": "an",
"collectionName": "Relaxing with friends",
"distance": "1324",
"country": "Russian Federation",
"Region": "North-West region",
"city": "Saint Petersburg"
},
{
"id": "123234344t5213",
"name": "N",
"image": "A",
"suggested": true,
"address": {
"longitude": "30.31821",
"latitude": "59.93605",
"formatted": ["Nevskiy prospekt 15, Saint Petersburg",
"Russian Federation"
]
},
"tags": ["fish",
"french",
"family"
],
"category": "$$$$",
"description": "Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda. ",
"shortDescription": "ab",
"collectionName": "Evening with a family",
"distance": "556",
"country": "Russian Federation",
"Region": "North-West region",
"city": "Saint Petersburg"
}]}}
Here is a snippet of my initial JSON data (it isn't completed, for example, at this moment there is only a string for an image). The data is used throughout the whole app (in a table view, separate views etc.). For example, I use it to populate the table view, use it in a mapView and in other UIViewController subclasses. Also, I need an ability to filter it and to search through it. Currently, I'm doing that by decoding the whole JSON and adding it to an array, and then, I filter that array. But I guess, that isn't the best choice when you have a large amount of data with images.
And one more thing, in Core Data it is possible to set batch requests, so it will initially fetch only some amount of data. It works fine with table views, because when you scroll them, Core Data automatically fetches new data to populate cells. Is it possible to do something like that with firebase, or should I read all data at once?
I've also read that Firebase doesn't require to save array-like data, but there are several ways to solve that issue. It is important to me, because I do need some part of the data to be in an array.
Hopefully this will provide some direction, pardon the length.
Right of the bat, there are usually better ways to store data in Firebase than arrays; arrays are not searchable, editable or addable and if you want to change something the entire array will need to be overridden. Please see Arrays Are Evil.
Secondly Denormalizing Data Is Normal in Firebase. What this means is that when data gets too 'deep' it's much more difficult to query for the data you want. Generally flatter is better - depending on what you want to get out of Firebase.
Third item is there are 100 different ways to work with the data in your question, I'll present two; one to demonstrate conceptually how to write the data and the second is probably a better option.
Here's how to write your data in a brute force kind of way
let addressDict = [
"longitude": "30.31527",
"latitude": "59.93688",
"formatted1": "Nevskiy prospekt 10, Saint Petersburg",
"formatted2": "Russian Federation"
]
let tagsDict = [
"fish": true,
"italian": true,
"friends": true
]
let restaurantDict = [
"name": "Grand Royal",
"suggested": true,
"address": addressDict,
"tags": tagsDict,
"category": "$$$$",
"description": "Lorem ipsum dolor si.",
"shortDescription": "an",
"collectionName": "Relaxing with friends",
"distance": "1324",
"country": "Russian Federation",
"Region": "North-West region",
"city": "Saint Petersburg"
] as [String : Any]
let restaurantsRef = self.ref.child("restaurants").childByAutoId()
restaurantsRef.setValue(restaurantDict)
Running this code will result in a JSON structure similar to your structure. Note that the restaurant key (KzEIkF6nxgWH1nA8B2D) was created automatically when the data is written so that's how the restaurant would be referred to in other structures, by its key.
"restaurants" : {
"-KzEIkF6nxgWH1nA8B2D" : {
"Region" : "North-West region",
"address" : {
"formatted1" : "Nevskiy prospekt 10, Saint Petersburg",
"formatted2" : "Russian Federation",
"latitude" : "59.93688",
"longitude" : "30.31527"
},
"category" : "$$$$",
"city" : "Saint Petersburg",
"collectionName" : "Relaxing with friends",
"country" : "Russian Federation",
"description" : "Lorem ipsum dolor si.",
"distance" : "1324",
"name" : "Grand Royal",
"shortDescription" : "an",
"suggested" : true,
"tags" : {
"fish" : true,
"friends" : true,
"italian" : true
}
}
},
To query for all $$$$ restaurants:
//print all restaurants with $$$$
let restRef = self.ref.child("restaurants")
let query = restRef.queryOrdered(byChild: "category").queryEqual(toValue: "$$$$")
query.observeSingleEvent(of: .value) { snapshot in
for child in snapshot.children {
let snap = child as! DataSnapshot
print(snap)
}
}
While we can query for all restaurants that have a category == "$$$$", the address and tags node are too deep (which is not actually accurate, see Deep Query, but we're going with it for this example as the concept is sound).
So a better structure is
"restaurants" : {
"-KzEIkF6nxgWH1nA8B2D" : {
"Region" : "North-West region",
"category" : "$$$$",
"city" : "Saint Petersburg",
"collectionName" : "Relaxing with friends",
"country" : "Russian Federation",
"description" : "Lorem ipsum dolor si.",
"distance" : "1324",
"name" : "Grand Royal",
"shortDescription" : "an",
"suggested" : true,
}
},
"addresses"
"-KzEIkF6nxgWH1nA8B2D"
"formatted1" : "Nevskiy prospekt 10, Saint Petersburg",
"formatted2" : "Russian Federation",
"latitude" : "59.93688",
"longitude" : "30.31527"
"tags"
"-KzEIkF6nxgWH1nA8B2D"
"fish" : true,
"friends" : true,
"italian" : true
and the code to create it:
let restDict = [
"name": "Jay's Eatery",
"category": "$$$$"
]
let addressDict = [
"formatted1": "Anytown"]
let tagsDict = [
"fish": true,
"friends": true,
"italian": true
]
let restRef = self.ref.child("restaurants")
let addressesRef = self.ref.child("addresses")
let tagsRef = self.ref.child("tags")
let thisRestaurantRef = restRef.childByAutoId()
thisRestaurantRef.setValue(restDict, withCompletionBlock: { (error, snapshot) in
if error == nil {
let thisRestaurantKey = snapshot.key
addressesRef.child(thisRestaurantKey).setValue(addressDict)
tagsRef.child(thisRestaurantKey).setValue(tagsDict)
}
})
Now you can easily query for restaurants with tags of fish, latitude starting with 59 or name of Grand Royal using the query from above.
As you can see, when data in stored in Firebase, there no encoding or decoding involved.
Yes, Firebase can batch load data to populate an array to be used as a tableView datasource
Best practice is to create class object that represents data in your code and to the user, and leverage Firebase on the back in to store that data.
class RestaurantClass {
key = "" //"-KzEIkF6nxgWH1nA8B2D"
name = "" //"Grand Royal
etc
func init(withSnapshot: DataSnapshot) {
//populate the class vars from the snapshot
}
Then the query for $$$$ restaurants would be something like this:
let restRef = self.ref.child("restaurants")
let query = restRef.queryOrdered(byChild: "category").queryEqual(toValue: "$$$$")
query.observeSingleEvent(of: .value) { snapshot in
for child in snapshot.children {
let snap = child as! DataSnapshot
let rest = RestaurantClass(withSnap: snap)
self.myTableViewDataSourceArray.append(rest)
}
self.myTableViewDataSourceArray.reloadData()
}
There's a lot more but this should get you going in the right direction.
The takeaway from this answer is to leverage Firebase to store raw data on the backend - it's blisteringly fast, expandable and maintainable given the data is structured properly. Use classes in code that are populated with that back end data to be used as a datasource and present data to the user.
One final note is if you are working with locations, you're going to want a tool to make that easier. Check out GeoFire for more information.
EDIT:
To address a comment for clarification.
You don't exactly create Firebase data structures in code like you would create properties for a class or struct and it's nothing like a empty SQL table with headers. It's more how you tell Firebase how to write that data. So for example:
ref.child("users").child("uid_0").setValue("Leroy")
tells Firebase that within the users node, write a key: value pair of a string: string of uid: Leroy like this:
users
uid_0: "Leroy"
and
let aDict = ["user_name": "Leroy"]
ref.child("users").child("uid_0").setValue(aDict)
will result in telling Firebase that within the users node to write a key: value pair of a string: dictionary of uid: aDict. Note that aDict is a key: value pair itself of string: string (e.g user_name: Leroy)
users
uid_0
user_name: "Leroy"
I like to think of Firebase is a big Dictionary of key: value pairs where keys are always strings (avoid arrays!) and values are of Any type which could be strings, ints, etc or other Dictionaries.

Insert comments in Jira with Talend

During my searching, I would like advice about how to insert a comment in Jira issue via Talend Open Studio.
Here is my job :
So, I am trying to insert comment via Talend.
I use a tHttpRequest set like that :
uri is my string connection to get Jira account.
As it's a POST method, my header is Content-Type | application/json.
My post parameters are in a JSON file :
{
"fields": {
"project": {
"key": "TRL"
},
"summary": "A",
"description": "B",
"issuetype": {
"name": "Task"
},
"labels": ["Webapp"],
"reporter": {
"name": "x.x"
},
"assignee": {
"name": "x.x"
}
},
"body": "TEST1",
"visibility": {
"type": "role",
"value": "Administrators"
}}
When I launch this job, the following error appears :
As if the file of the response body was NULL, or maybe It's not the good manner to do the insert of the comment.
I clarify that with Insomnia(insomnia), the insertion of the comment works.
I try also the componant tRest but I don't succeed to link this one with tFileInputDelimited or tJIRAOutput.
Before to continue my work, I want to know if I am in the good direction ? Any clues ?
Thanks by advance,
Ale
I'd recommend using the tRest or tRestClient components. You can just send your JSON as "HTTP body" with these components.
On the JIRA side, you can get the necessary information here: https://developer.atlassian.com/jiradev/jira-apis
Assuming you're working with the on-premise JIRA, you'd use something like this:
URL: hostname + /rest/api/2/issue/{issueIdOrKey}/comment
HTTP Body:
{
"body": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eget venenatis elit. Duis eu justo eget augue iaculis fermentum. Sed semper quam laoreet nisi egestas at posuere augue semper.",
"visibility": {
"type": "role",
"value": "Administrators"
}
}
Don't forget about the Authentication

JQ - format JSON array appending values to a specific a value

I am trying to get this:
[
["John Black",[
["Lorem ipsum dolor sit amet.",27],
["Ut tempus lectus ut mi.",23]
]],
["Peter Pan",[
["Quisque pulvinar odio.",22],
["Nec ut lorem quis interdum elit.",32]
]],
["Gary Halbert",[
["Placerat aliquam.",17]
]],
["Richard Gere",[
["Porttitor commodo fermentum.",28]
]]
]
Till now, this is what I got:
export A=$(cat <<'EOL'
[
["John Black",["Lorem ipsum dolor sit amet.",27]],
["Peter Pan",["Quisque pulvinar odio.",22]],
["John Black",["Ut tempus lectus ut mi.",23]],
["Gary Halbert",["Placerat aliquam.",17]],
["Peter Pan",["Nec ut lorem quis interdum elit.",32]],
["Richard Gere",["Porttitor commodo fermentum.",28]]
]
EOL
)
echo "$A" | jq 'map({(.[0]): .[1]}) | add'
Resulting this:
{
"John Black": [
"Ut tempus lectus ut mi.",
23
],
"Peter Pan": [
"Nec ut lorem quis interdum elit.",
32
],
"Gary Halbert": [
"Placerat aliquam.",
17
],
"Richard Gere": [
"Porttitor commodo fermentum.",
28
]
}
I am using jq-1.5.
Any ideas? Thanks.
This is an appropriate use case for a reducer. Most of the below is related not to joining items under shared keys, but to getting them into the desired nested-list form:
jq -n '[
inputs |
reduce .[] as $item ({}; .[$item[0]] += [$item[1]]) |
to_entries |
.[] |
[.key, .value]
]' <<<"$A"
...yields as output (edited only for compactness with regard to whitespace):
[
["John Black", [["Lorem ipsum dolor sit amet.", 27], ["Ut tempus lectus ut mi.",23]]],
["Peter Pan", [["Quisque pulvinar odio.",22], ["Nec ut lorem quis interdum elit.", 32]]],
["Gary Halbert", [["Placerat aliquam.", 17]]],
["Richard Gere", [["Porttitor commodo fermentum.", 28]]]
]
the Couchdb engine is append only, it means that each document will append into a file manager by Couchdb, and each file is related to a db.
to use properly think how to avoid updates in the same document, remember all revisions will be storage.
my suggestion for each document.
{
"name": "John Black",
"entries": [
{
"test": "Lorem ipsum dolor sit amet.",
"value": 27
},
{
"text": "Ut tempus lectus ut mi.",
"value": 23
}
],
"type": "user"
}