React get JavaScript Object from JSON file? - json

The issue is that I'm trying to get a JavaScript object like the following:
[
"id" : 11,
"name" : "Peter"
"other": {
"id": 22,
"item": 534
},
"main": false
]
Since I want to get this via reactjs: I trying to do this:
http.get(API.BASE_URL + API.USER_INFO)
.accept('Application/json')
.end((err, res) => {
//console.log(x);
console.log(err);
console.log(res);
});
When I try a normal json string I get the right result, but with this javascript object I get:
Error: Parser is unable to parse the response
undefined
Has anyone come across this before? Any idea?

What you're trying to parse isn't valid JSON (as well as JavaScript) because you've written it out as an array, but still use key/value pairs as if it were an object. Try this instead:
{
"id": 11,
"name": "Peter",
"other": {
"id": 22,
"item": 534
},
"main": false
}

Related

How to add new object in a json file using RobotFrameWork

I am trying to add a new bloc to my JSON
I have this JSON that I got after a GET :
{
"name": "John",
"age": 30,
"Deleted": false
}
What I want to do is to add a block trips to this Json using RobotFrameWOrk to get this result:
{
"name": "John",
"age": 30,
"trips": [
{
"dateTime": "2020-01-24T15:28:29.7073727Z",
"FirstName": "John",
"Comment": "TestMe"
}
],
"Deleted": false
}
My questions are:
The object Trips doesn't exist I have to create it manually
and then I should add this object to my JSON after the age and before Deleted
${JsonFinall}= Add String ${FirstJson} ${BlockTrips}
Log ${JsonFinall}
I imagine it would be something like that but I am blocked on the first step I don't know how to create and fill the object trips?
Do you think that I have to work with Regex?
Thanks for your help
***********************EDIT**********
I tried with add object to json : `# Bloc ActionR
${jsonFinall}= Add Object To Json ${JsonAvecAR} Course/AR.txt`
the file AR.txt is the file where I put my object trips :
"trips": [
{
"dateTime": "2020-01-24T15:28:29.7073727Z",
"FirstName": "Alicia",
"Comment": "TestMe"
}
],[![enter image description here][1]][1]

Accessing JSON array within JSON object in VBA Excel using VBA-JSON

I am working on VBA macros to access live data from a website through API calls. I am using VBA-JSON library for it. There are mainly two scenarios when fetching data:
Scenario #1 (we can see data is a JSON array):
{
"success": true,
"data": [
{
"id": 4,
"creator_user_id": {
"id": 162,
"name": "ASD",
"email": "email id"
},
"user_id": {
"id": 787878,
"name": "XYZ",
"email": "email id"
},
...
}
]
}
In the scenario 1 I can fetch values within data array by using For Each loop in VBA Excel through VBA-JSON library.
Scenario #2:
{
"success": true,
"data": {
"id": 123,
"name": "ABC",
"options": [
{
"id": 119,
"label": "Name1"
},
{
"id": 120,
"label": "Name2"
}
],
"mandatory_flag": false
}
}
But in 2nd scenario I can not access data within data array, because JSON data array is within JSON object. For example I want the value of id: 120 which must return Name2, thus I want to access value of label which will return Name2.
I tried many ways, but can not get it. Please anyone can tell me how this can be done in VBA Excel?
Any help appreciated.
Using the VBA-JSON library, you can access the value you want by calling:
Set Parsed = JsonConverter.ParseJson(<yourjsonstring>)
Debug.Print Parsed("data")("options")(2)("label")

Parsing Different Json Objects in WP8

Please help me in parsing this Json sample as I'm not able to parse it because of the complexity of it as well as different objects inside it. I'm able to parse Json when a list of same objects & same structure but not like the one below.
[
{
"notificationBrowserHead":
{
"notificationId": 4,
"notificationType": "NEW_PRODUCT",
"creationTime": 1421933381000,
"notificationNormalUserId": 4,
"notificationViewed": false
},
"brandIdAndNameHolder":
{
"brandId": 1,
"name": "B1"
},
"brandLogo": null,
"productIdAndNameHolder":
{
"productId": 1,
"name": "JK product1"
}
},
{
"notificationBrowserHead":
{
"notificationId": 2,
"notificationType": "USER_INT_COMMENT",
"creationTime": 1421924403000,
"notificationNormalUserId": 2,
"notificationViewed": false
},
"uploadId": 22,
"uploadThumbnail": "/mediaUrl/location/thumbNail",
"uploadDescription": "upload 1 location desc",
"notificationCreator":
{
"normalUserId": 90,
"displayName": "amit"
},
"uploadRemoved": false
},
{
"notificationBrowserHead":
{
"notificationId": 1,
"notificationType": "NEW_LOCATION_VOTE",
"creationTime": 1421924403000,
"notificationNormalUserId": 1,
"notificationViewed": false
},
"locationIdAndNameHolder":
{
"locationId": 11,
"name": "Current King JK"
},
"locationLogo": null
}
]
Any help would be truly appreciated.
I presume that you receive different set of json properties when your NotificationType varies.
Solution 1:
Define all your members(the collection of all your properties that you receive for different types of notification) in a Class and use it for DeSerialization, so that the unwanted properties for your particular notification type will be null.
Solution 2:
Parser manually. Newtonsoft json documentation here
Make class "Notifications (or something)" and put inside everything you got back from json2csharp.com site, then use this framework http://www.newtonsoft.com/json to deserialize data as you download it from server and you should be able to get notificationType by Object.Notificationbrowserhead[x].notificationType or similar.

Use $resource of AngularJS to find specific element in json Array

I am new to AngularJS. Trying to get specific element from a JSON array via $resource.
The structure of JSON file staffs.json is like:
[{
"id": 0,
"facility_id": [0],
"name": "Tim",
"role_id": 0
},
{
"id": 1,
"facility_id": [0],
"name": "Duncan",
"role_id": 0
},
{
"id": 2,
"facility_id": [0],
"name": "Tony",
"role_id": 1
},
{
"id": 3,
"facility_id": [0],
"name": "Parker",
"role_id": 1
},
{
"id": 4,
"facility_id": [0],
"name": "Manu",
"role_id": 2
},
{
"id": 5,
"facility_id": [0],
"name": "Ginobili",
"role_id": 2
},
{
"id": 6,
"facility_id": [0],
"name": "Tiago",
"role_id": 3
},
{
"id": 7,
"facility_id": [0],
"name": "Splitter",
"role_id": 3
}]
I am trying to get a staff whose name is "Tiago".
The code is:
var url = 'data/staffs.json';
var username = 'Tiago';
users = $resource(url);
users.get({name: username}, function(data){
alert(data.name);
});
It seems the alert() function inside the get() never gets called. However if I changed the method from users.get() to users.query(), it can get the list of the staffs. I guess this is because the data inside the JSON file is an array, so the query() which is used to get array works, while the get() does not work because it is not for array operation. Am I correct?
I am just wondering if I have to use query() get the whole array and match the elements one by one until I find the one with the same name, or there are some simpler ways to get the element I want.
Thanks
AngularJS resource has a separate query function to avoid JSONP vulnerability for arrays. You have two options:
get all and find the element in the array on the client side
add extra API endpoint for single user and fetch it by the name
I vote for option two, since you don't have to send everything over the wire and you use server (DB) to get the specific user. Server software is optimised for that.
Your best bet would by fetching data with the query() method, then using indexOf()
var url = 'data/staffs.json';
var username = 'Tiago';
users = $resource(url);
users.get({name: username}, function(data){
dataOfMyUser = data.map(function(cur) { return cur.name }).indexOf(username);
alert(dataofMyUser);
});

JSON Parsing Error

I got problem. I have this JSON automatically generated by Open Flash Chart php library. The problem is, OFC report JSON Parse Error [Syntax Error] while test result using http://www.jsonlint.com/ report that my JSON is fine. But, w3c parser report error too:(
Any help?
Here's the JSON:
{
"title": "Followers Trend",
"elements": [
{
"type": "area_hollow",
"fill-alpha": 0.35,
"values": [
],
"colour": "#5B56B6",
"text": "Followers",
"font-size": 12
}
],
"x_axis": {
"colour": "#A2ACBA",
"grid-colour": "#D7E4A3",
"offset": false,
"steps": 4,
"labels": {
"steps": 2,
"rotate": "vertical",
"colour": "#A2ACBA",
"labels": [
]
}
},
"x_legend": {
"text": "Week Trend (2009-08-17 - 2009-08-24)",
"style": "{font-size: 20px; color: #778877}"
},
"y_axis": {
"min": 0,
"max": 150,
"steps": 30
}
}
A few things I learned while playing with JSON is:
If you have validate the JSON on various JSON validation services and the result is GOOD. But, when you failed to eval it, try to wrap your JSON using ( and ) => ({jsondata})
var json = eval( "(" + jsonString + ")" );
NEVER build the JSON yourself. It's a gate to failure. Always use official or popular JSON library (depending on your language). For example:
On PHP: use json_encode()
On Java Android: use org.json.JSONObject
A list of all other available library to play with JSON is listed in JSON official page.
To display and format JSON data, you can use JSONViewer.
I think the w3c parser is having issues, I couldn't even get it to parse this:
{
"title" : "Followers Trend"
}
It gave me this error:
Validation errors:
lexer couldn't parse at "{
"title" : "Followers Trend"
}"
http://json.bloople.net helps you visualise the code to find and correct errors.
try this code, JSON.parse() method is not able to handle string which is in a
single quote as a value in the right-hand side. also if you want to handle the
UTF-8 character code, then it will do.
parseJSON = function() {
var data = {};
var reader = new FileReader();
reader.onload = function() {
try {
data = JSON.parse(reader.result.replace(/'/g, "\""));
console.log(data)
} catch (ex) {
console.log('error' + ex);
}
};
reader.readAsText(fileSelector_test[0].files[0], 'utf-8');
}