Access json data based on dynamic route nextjs - json

I have a json file that contains content for several different pages that are under a "service" category. I use dynamic routes in nextJS by having a file as "[serviceId].tsx", this routing works. However I have a json file where I want to use the [serviceId] provided in the route to access information.
I have the following code in my [serviceId].tsx file:
const json = jsonFile.services
const router = useRouter()
const serviceId = router.query.serviceId
return (
<div>
<ArticleWithPicture title={content.title} description={content.description}/>
</div>
)
}
My json file looks similar to this (ive edited it to be more clear for this example):
{
"serviceId":
[
{
"service1": {
"id": "xx",
"title": "xxx",
"description": "xx",
"featuredCompany":
[
{ "id": "1",
"name": "xxx",
"companyPageURL": "/",
"imagePath": "xxx",
"description": "xxx",
"additionalServices": {
"service1": "xxx",
"service2": "xxx"
},
"instagramURL":"/",
"twitterURL": "/"
}
]
}
},
{
"service2": {
"id": "xxx",
"title": "xxx",
"description": "xxx",
"featuredCompany":
[
{ "id": "1",
"name": "xxx",
"companyPageURL": "/",
"imagePath": "xxx",
"description": "xxx",
"additionalServices": {
"service1": "xxx",
"service2": "xx"
},
"instagramURL":"/",
"twitterURL": "/"
}
]
}
}
]
}
Basically, each Service has the content for each indiviual page. So I want to dynamically set for instance the title of my component "ArticleWithPicture" based on the corresponding title in my json file based on the serviceId that I get from router.query.serviceId. However when I try the following code:
<ArticleWithPicture title={json.{serviceId}.title}/>
I get error (this is due to how I use "{}" within a "{}", is there a way to do this better?
But I also cannot access it if I do eg:
const title = json.serviceId.title
or (what is what I actually want to do ie: query the json file based on my serviceId provided by "router.query.serviceId")
const title = json.{serviceId}.title
I guess something might be wrong with either my json file structure or how I try to access it. Any advice would be appreciated.
Thanks!

I'm assuming the JSON you provided is your entire jsonFile.
If the JSON you provided is just jsonFile.services, then change any uses of jsonFile to jsonFile.services
and update the type.
The format of the JSON isn't great for your use case because there's a lot of unnecessary wrapping.
With your current JSON
Assuming you cannot modify the format of the JSON, you would have to find the service from the serviceId array:
function getService(json, serviceId) {
return json.serviceId
.find((serviceWrapper) => serviceWrapper[serviceId] !== undefined)
?.service;
}
A fully typed example:
type Service = {
id: string
title: string
description: string
// ...
};
// you don't have to use this, I just included it for clarity
type JsonFile = {
serviceId: {
[serviceId: string]: Service
}[]
};
function getService(json: JsonFile, serviceId: string): Service | undefined {
return json.serviceId
.find((serviceWrapper) => serviceWrapper[serviceId] !== undefined)
?.service;
}
// declare const jsonFile: JsonFile;
export default function ServicePage() {
const router = useRouter();
const serviceId = router.query.serviceId as string;
const content = getService(jsonFile, serviceId);
if (!content) return (
<div>
{'Article doesn\'t exist.'}
</div>
);
return (
<div>
<ArticleWithPicture title={content.title} description={content.description} />
</div>
);
}
With better JSON
An example JSON that would need less unwrapping is:
{
"service1": {
"id": "xx",
"title": "xxx",
// ...
},
"service2": {
"id": "xxx",
"title": "xxx",
// ...
}
}
type JsonFile = {
[serviceId: string]: Service
}
Then you would be able to just do jsonFile[serviceId] or jsonFile.services[serviceId] to get a service.

Related

getting the error like JSON schema is not correct. Enter specified JSON scehma.,Create an Array of Favorite fruits Object

0
I have the following assessment which is to Create Array of Favorite Food items object in data.json file.
The Array of Objects should have the following fields :
Name
Type
Price
After writing the JSON data, this file should be imported in loopobject.js.
I tried the above request with the below data.json
data.json
"{[{\"Name\":\"Apple\",\"Type\":\"fruit\",\"Price\":123},{\"Name\":\"pizza\",\"Type\":\"italian\",\"Price\":360},{\"Name\":\"burger\",\"Type\":\"mac&cheese\",\"Price\":321},{\"Name\":\"jangri\",\"Type\":\"sweet\",\"Price\":329}]}"
loopObject.js
var json = require('./data.json');
json.forEach(function(object) { console.log(object.Name); });
verify.js
const Joi = require('joi');
const fss =require('fs');
const schema = Joi.array().min(3).has({
Name: Joi.string().required(),
Type: Joi.string().required(),
Price: Joi.number().required(),
});
var data;
try{
data = require("./data.json");
}catch(e)
{
data={};
}
var XMLWriter = require('xml-writer');
xw = new XMLWriter;
const result = Joi.validate(data, schema);
// You can also pass a callback which will be called synchronously with the validation result.
Joi.validate(data, schema, function (err, value) {
if(err==null)
{ console.log("JSON is valid.");
}else{
console.log("JSON schema is not correct. Enter specified JSON scehma.");
}
});
i have tried couple of ways, everything looks good,but don't know where i am doing mistake. Could you please help on this??
The JSON format is not correct, try this one:
data.json
[
{
"Name": "someName",
"Type": "someType",
"Price": 123
},
{
"Name": "someName",
"Type": "someType",
"Price": 123
},
{
"Name": "someName",
"Type": "someType",
"Price": 123
},
{
"Name": "someName",
"Type": "someType",
"Price": 123
}
]
The JSON data describes an array, and each element of that array is an object.

get json value object from mongodb

I have formData node that has dynamic jsonObject value in mongodb
{
"_id": {
"$oid": "5a71fea0f36d2848ae4f8f0a"
},
"formData": {
"pages": [
{
"name": "page1",
"questions": [
{
"type": "comment",
"name": "about",
"title": "Please tell us about your main requirements "
}
]
}
]
},
"editorId": "59678e58f36d2842f777bc48",
"datetimeSubmit": "2018/01/15"
}
I write a node API to fetch the data from mongodb, it only display ids, editorI and datetimesubmit nodes, but it ignores the formData(jsondata) field.
const Model = require('./myModel');
module.exports = {
getData: function (callback) {
Model.find({}, (err, jsonObj) => {
callback(null, {
data: jsonObj
})
})
}
}
looks like the model.find() doesn't return jsonObject value?
thanks
got my own question fixed, basically, i should also define the data type as JSON in schema, otherwise, will be ignored.

how to get length of couch.get(data,headers,status)

I tried to create nodejs with expressjs by connecting to couchdb . For that I have used nodejs-couch installed using npm.
app.get('/', function(req, res) {
couch
.get(dbName, viewUrl)
.then(
function(data, headers, status) {
console.log(data.length);
var data1 = data.data.rows;
console.log(data1);
res.send(data1.length);
},
function(err) {
res.send(err);
}
);
});
my json data :
[
{
"id": "7a6a4d9cf76efc00977ca63ca3002a31",
"key": "7a6a4d9cf76efc00977ca63ca3002a31",
"value": {
"name": "nagarjuna",
"email": "nagarjuna#gmail.com",
"password": "12345",
"mobile": "987654321",
"rev": "8-c90103f1fca709ae314a684c767c97dc"
}
},
{
"id": "7a6a4d9cf76efc00977ca63ca3003743",
"key": "7a6a4d9cf76efc00977ca63ca3003743",
"value": {
"name": "sandeep",
"email": "sandeep#gmail.com",
"password": "54321",
"mobile": "9876541",
"rev": "1-fd6e667b87794adea78e169bc46016e6"
}
}
]
I had written get function to fetch all customer information. If I print console.log(data.data.rows); I am able fetch json data. But I want to get length and attribute values from json. But when I print console.log(data.length); it getting undefined.
Can any one suggest me. Any suggestions would be appreciated.
The result from the database contains a lot of different information, like meta information and the results. Here is a trimmed down representation of what you're looking for
var data = {
data: {
rows: [{row1},{row2}...];
}
}
So for you to be able to get the length of rows from the database, you'll have to dig into the right attribute in the object like this:
var length = data.data.rows.length;

Getting key and value from JSON with angular2

I am looking for best solution how to work with JSON in my angular2 app.
My JSON is:
{
"rightUpperLogoId": {
"id": 100000,
"value": ""
},
"navbarBackgroundColorIdCss": {
"id": 100001,
"value": ""
},
"backgroundColorIdCss": {
"id": 100002,
"value": ""
},
"translationIdFrom": {
"value": "90000"
},
"translationIdTo": {
"value": "90055"
}
}
This JSON is something like configuration file for UI of app. In my application, I want to get id from rightUpperLogoId, it is 100000. With this id I need to do GET task on my backend REST api and the returned value I would like to set to value. Thank you
You could leverage Rx operators like the flatMap one with Observable.forkJoin / Observable.of.
Here is a sample:
this.http.get('config.json')
.map(res => res.json())
.flatMap(config => {
return Observable.forkJoin(
Observable.of(config),
// For example for the request. You can build the
// request like you want
this.http.get(
`http://.../${config.rightUpperLogoId.id}`)
);
})
.map(res => {
let config = res[0];
let rightUpperLogoIdValue = res[1].json();
config.rightUpperLogoId.value = rightUpperLogoIdValue;
return config;
})
.subcribe(config => {
// handle the config object
});
This article could give you more hints (section "Aggregating data"):
http://restlet.com/blog/2016/04/12/interacting-efficiently-with-a-restful-service-with-angular2-and-rxjs-part-2/

Ember Data One to One Relationship Record Creation Fails

I receive the following error when I use Ember Data to create records from a JSON response. What gives? I am following what the docs state.
Uncaught Error: Assertion Failed: Ember Data expected a number or string to represent the record(s) in the `user` relationship instead it found an object. If this is a polymorphic relationship please specify a `type` key. If this is an embedded relationship please include the `DS.EmbeddedRecordsMixin` and specify the `user` property in your serializer's attrs object.
JSON being parsed:
[
{
"id": 76,
"title": "Title",
"shipped": 0,
"date": "2015-05-21T05:00:00.000Z",
"user": {
"firstName": "First Name",
"lastName": "Last Name",
"email": "hellothere#gmail.com",
"id": 1
}
}
]
Shipment Model:
import DS from 'ember-data';
export default DS.Model.extend({
title: DS.attr('string'),
user: DS.belongsTo('user', { async: false })
});
Route:
import Ember from 'ember';
export default Ember.Route.extend({
beforeModel: function() {
if(!localStorage.accessToken) {
this.transitionTo('login');
}
},
model: function() {
var shipmentObjects = [];
var App = this;
Ember.$.getJSON('http://localhost:1337/subscription/1/shipments/upcoming', function(shipments) {
shipments.forEach(function(data) {
var shipment = App.store.push('shipment', data);
shipmentObjects.pushObject(shipment);
});
});
return shipmentObjects;
}
});
You can create a custom serializer, if you can't modify your json response and manage to arrange data in other way
App.MODELNAMESerializer = DS.ActiveModelSerializer.extend({
extract: function(store, type, payload, id, requestType){
var shipments = [];
//CREATE A NEW PAYLOAD THAT EMBER CAN READ
var _payload = { };
return this._super(store, type, _payload, id, requestType);
}
});
Your json should look something like this
{
shipments: [
{
"id": 76,
"title": "Title",
"shipped": 0,
"date": "2015-05-21T05:00:00.000Z",
"user_id": 1,
}
],
"users": [
{
"firstName": "First Name",
"lastName": "Last Name",
"email": "hellothere#gmail.com",
"id": 1
}
]
}
Read the error message. It could hardly be clearer. By default, Ember Data expects an association to be represented by an ID. If the association is instead embedded, you must tell Ember Data that. You'll need something like:
// serializers/shipment.js
export default ApplicationSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
user: { embedded: 'always' }
}
});
And remove the {async: false}, since the data is embedded right there.
See http://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html.