Replacing Slashes in JSON URL Data - json

I want to replace "\\" to "/" in productImage path, my code as below I used replace method but didn't work, waiting for your help thank you
const response = {
count: docs.length,
products: docs.map(doc => {
return {
name: doc.name,
price: doc.price,
productImage: doc.productImage,
_id: doc._id,
request: {
type: "GET",
url: url + "/products/" + doc._id
}
};
})
};
My JSON Output
{
"name": " Sample Product",
"price": 45,
"productImage": "uploads\\2018-05-02T09-12-59.937Zahmet.jpg",
"_id": "5ae9811be170eb0a78500088",
"request": {
"type": "GET",
"url": "http://localhost:3000/products/5ae9811be170eb0a78500088"
}
},

You can split that value by \\, you'll get an array, join that array with /
var obj = {
"name": " Sample Product",
"price": 45,
"productImage": "uploads\\2018-05-02T09-12-59.937Zahmet.jpg",
"_id": "5ae9811be170eb0a78500088",
"request": {
"type": "GET",
"url": "http://localhost:3000/products/5ae9811be170eb0a78500088"
}
}
obj.productImage = obj.productImage.split("\\").join("/");
console.log(obj)

Related

Firefox gives "301 Moved permanently" error on Http Request

I am currently developping an Angular 4 chat application, which make severals HTTP request.
On Google Chrome or Opera browser, all requests work fine but when I test my app on Firefox, one of them doesn't pass. I have already cleared my cache many times but the problem persists.
this.chatWebService.getLatestConversations(params).subscribe(
(response: CustomHttpResponse<ConversationModel[]>) => {
this.chatSharedService.setDiscussionList(response.data);
},
(errorResponse: HttpErrorResponse) => {
console.log(errorResponse)
});
And the request:
public getLatestConversations(p: { filter: string, search: string, page_index: number, page_count: number }): Observable<{}> {
const url = `${this.messagesUrl}?filter=${p.filter}&search=${p.search}&page_index=${p.page_index}&page_count=${p.page_count}`;
return this.http.get(url, { params: this.createHttpParams(p) });
}
private createHttpParams(params: {}): HttpParams {
const searchParams = new HttpParams();
const keys = Object.keys(params);
keys.forEach(key => searchParams.append(key, String(params[key])));
return searchParams;
}
On Firefox, this code gives me this error:
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of
the JSON data
Here is a sample of the returned JSON data:
{
"data": [
{
"type": "user",
"id": 76,
"name": "User 1",
"slug": "razx6k5nuser",
"muted": false,
"messages": [
{
"content": "Hi there",
"media": false,
"sent": 1516372902,
"read": true,
"sender": {
"id": 76,
"slug": "razx6k5nuser",
"lastname": "User lastname",
"firstname": "User first name",
"phoneNumber": ""
}
}
]
},
{
"type": "user",
"id": 71,
"name": "User 2",
"slug": "volc6p1suser",
"muted": false,
"messages": [
{
"content": "new message",
"media": false,
"sent": 1516358686,
"read": false,
"sender": {
"id": 77,
"slug": "razv6i2auser",
"lastname": "User lastname",
"firstname": "User first name",
"phoneNumber": ""
}
}
]
}
],
"meta": {
"page": "1",
"total": 18,
"totalNotRead": 1,
"totalMuted": 0
}
}
According to some errors I found on Google, it seems be solved by adding some headers for each request, so I have already added some headers on each of request with the interceptor, like this:
const request = req.clone({
setHeaders: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
But it still doesn't work. Can someone help me? Thank you in advance.

How to display data from a json file in angularjs?

I have a json something like this
{
"count": 67,
"0": {
"id": "2443",
"name": "Art Gallery",
"category": {
"id": "2246",
"name": "Gifts & Memories"
},
"deckLocation": [
{
"id": "2443",
"deck": {
"deckNo": "7",
"deckName": "Promenade "
},
}
]
},
"1": {
"id": "7198",
"name": "Captain's Circle Desk",
"category": {
"id": "352",
"name": "Other Services"
},
"deckLocation": [
{
"id": "7198",
"deck": {
"deckNo": "7",
"deckName": "Promenade "
},
},
{
"id": "7198",
"deck": {
"deckNo": "7",
"deckName": "Promenade "
},
}
]
}
}
I want to display all names which is inside the "0", "1" array. I can able to list a specific name but not all. The fist name will display which I written in the following code. But I need to display all 0, 1, 2, 3 etc names dynamically.
data[0].name
Please help me.
Thank you.
use ng-repeat function to do so.
<div ng-repeat = "names in data">
<P>{{names.name}}</P>
</div>
Let us say you have a service like this:-
var todoApp = angular.module("todoApp",[]);
todoApp.factory('dbService', ['$q','$http',function ($q , $http) {
var service ={};
service.getUrl = function (urlToGet) {
var svc=this;
var deferred = $q.defer();
var responsePromise = $http.get(urlToGet);
responsePromise.success(function (data, status, headers, config) {
deferred.resolve(data); });
responsePromise.error(function (data, status, headers, config) {
deferred.reject({ error: "Ajax Failed", errorInfo: data });});
return (deferred.promise);
}
return service;
}]);
And you want to load a file named '/js/udata.json'. Here is how in you controller you can load this file:-
todoApp.controller("ToDoCtrl", ['$scope','$timeout','dbService',function($scope, $timeout, dbService)
{
$scope.todo={};
$timeout(function(){
dbService.getUrl('/js/udata.json').then(function(resp){
$scope.todo=resp;
});},1);
};
Hope this helps!
You have data[0].name right?
then why don't you loop through that to get all the name elements in those arrays.
like...
for(i=1;i<data.length;i++)
{
console.log(data[i].name);
}

problems parsing json response from Neo4j REST API query

After inserting a node containing 2 properties into a Neo4j database, how do I extract the properties ("name" and "phone") from a REST API query response? My script for querying the database is:
<script>
function query_database()
{
var restServerURL = "http://localhost:7474/db/data"; //local copy on windows machine
$.ajax({
type:"POST",
url: restServerURL + "/cypher",
accepts: "application/json",
dataType:"json",
data:{
"query" : "start n = node(*) return n",
"params" : {}
},
success: function(data, xhr, textStatus){
//alert("query success!");
//process query results here
alert(JSON.stringify(data, null, 4));
},
error:function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
}//end of query database
The "alert(JSON.stringify(data, null, 4));" displays the following:
{
"columns": [
"n"
],
"data": [
[
{
"paged_traverse": "http://localhost:7474/db/data/node/3761/paged/traverse/{returnType}{?pageSize,leaseTime}",
"outgoing_relationships": "http://localhost:7474/db/data/node/3761/relationships/out",
"data": {
"phone": "123.456.7890",
"name": "jeff "
},
"traverse": "http://localhost:7474/db/data/node/3761/traverse/{returnType}",
"all_typed_relationships": "http://localhost:7474/db/data/node/3761/relationships/all/{-list|&|types}",
"all_relationships": "http://localhost:7474/db/data/node/3761/relationships/all",
"property": "http://localhost:7474/db/data/node/3761/properties/{key}",
"self": "http://localhost:7474/db/data/node/3761",
"properties": "http://localhost:7474/db/data/node/3761/properties",
"outgoing_typed_relationships": "http://localhost:7474/db/data/node/3761/relationships/out/{-list|&|types}",
"incoming_relationships": "http://localhost:7474/db/data/node/3761/relationships/in",
"incoming_typed_relationships": "http://localhost:7474/db/data/node/3761/relationships/in/{-list|&|types}",
"extensions": {},
"create_relationship": "http://localhost:7474/db/data/node/3761/relationships"
}
]
]
}
Much thanks,
Jeff
In your example, you'd get the name and phone from the response data object like this:
var name = data.data[0][0].data.name;
var phone = data.data[0][0].data.phone;
alert("Name is " + name + "\nPhone is " + phone);
JSFiddle here.

Validate Json Schema

I'm getting an error when using json-schema-validator API v4.
I try to do :
final JsonValidator validator = new JsonValidator(JsonLoader.fromPath("schema.json"));
ValidationReport report = validator.validate(data);
but every time I get an error : # [schema]: unknown keyword contacts
schema.json :
{
"contacts": {
"description": "The list of contacts",
"type": "array",
"optional": true,
"items": {
"description": "A contact",
"type": "object",
"properties": {
"givenName": {
"description": "Person's first name",
"type": "string",
"maxLength": 64,
"optional": true
},
"familyName": {
"description": "A person's last name",
"type": "string",
"maxLength": 64,
"optional": true
}
}
}
}
}
Regards
As far as I can intuit, your data looks like this-> json_data={"contacts":array}. If this is true, basically your outermost thing is an object (basically the full json object itself), for which you "might" need to define the schema starting from the "top level root" of your json as->
schema.json:
{
"description": "the outer json",
"type": "object",
"properties": {
"contacts": {
"description": "The list of contacts",
"type": "array",
"optional": true,
"items": {
"description": "A contact",
"type": "object",
"properties": {
"givenName": {
etc.....
Forgive me for rough indentations. Also, I have not tested this, please see if it works, if it does not, I would suggest you to provide your json_data (example at least) and the API's examples so that one can try to locate where what is wrong.
Use AVJ. Instead of having your data validation and sanitization logic written as lengthy code, you can declare the requirements to your data with concise, easy to read and cross-platform JSON Schema or JSON Type Definition specifications and validate the data as soon as it arrives to your application.
// validationSchema.js
import Ajv from "ajv";
import addFormats from "ajv-formats";
import ajvErrors from "ajv-errors";
const schemas = {
newUser: {
{
type: "object",
properties: {
lastName: {
type: "string",
minLength: 1,
maxLength: 255
},
firstName: {
type: "string",
minLength: 1,
maxLength: 255
},
description: {
type: "string"
},
birthday: {
type: "string",
format: "date-time"
},
status: {
type: "string",
enum: ["ACTIVE", "DELETED"]
},
},
required: ["name"]
}
}
};
const ajv = new Ajv({ allErrors: true });
addFormats(ajv);
ajvErrors(ajv /*, {singleError: true} */);
const mapErrors = (errorsEntry = []) => {
const errors = errorsEntry.reduce(
(
acc,
{ instancePath = "", message = "", params: { missingProperty = "" } = {} }
) => {
const key = (instancePath || missingProperty).replace("/", "");
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(`${key} ${message}`);
return acc;
},
[]
);
return errors;
};
const validate = (schemaName, data) => {
const v = ajv.compile(schemas[schemaName]);
let valid = false,
errors = [];
valid = v(data);
if (!valid) {
errors = mapErrors(v.errors);
}
return { valid, errors };
};
export default { validate };
You can validate it like this:
import validationSchema from "your_path/validationSchema.js"
const user = {
firstName: "",
lastName: "",
....
};
const { valid, errors = [] } = validationSchema.validate("newUser", user);
if(valid){
console.log("Data is valid!");
} else {
console.log("Data is not valid!");
console.log(errors);
}

Extract Json data on client side

I have following JSON data coming to client. I need to extract the data somehow so I can loop through it to get all name & count values.
{
"summarydata": {
"rows": [
{
"name": "Cisco0 Webinar US",
"count": "1"
},
{
"name": "Resource Nation CC",
"count": "1"
},
{
"name": "test",
"count": "10"
},
{
"name": "test",
"count": "2"
},
{
"name": "Vendor Seek",
"count": "1"
}
]
}
}
$.extend($.jgrid.defaults,
{ datatype: 'jsonstring' },
{ ajaxGridOptions: { contentType: "application/json",
success: function (data, textStatus) {
if (textStatus == "success") {
var thegrid = $("#BuyBackGrid")[0];
thegrid.addJSONData(data.data);
var summaryresult = $.parseJSON(data.summarydata.rows[0]);
alert(summaryresult );// this gives me null
alert(data.summarydata.rows[0].name); //this gives me first name element which is "Cisco0 Webinar US" in my case.
// alert($.parseJSON(data).summarydata.rows[0].name);
}
} //end of success
}//end of ajaxGridOptions
});
Leveraging jQuery...
The $.getJSON() function parses a local JSON file and returns it as an object.
$.getJSON("myJSON.js", function(json){
alert(json.summarydata.rows[0].name);
});
You could also just do this, using the JSON library for javascript (the object is also standard in most recent browsers).
alert(JSON.parse(myJSONString).summarydata.rows[0].name);