JSON object parse issue on react - javascript

json = "{ elements: [ {type: 'radiogroup', choices: ['Yes','No','Maybe','Never'], isRequired: true, name: 'Test_01', title: 'Do you like ice cream?' }],showQuestionNumbers: 'off'}";
json = JSON.stringify(json);
model = new Model(json);
it dosen't recognise the json object when it have quotes on
var json = "{ elements: [ {type: 'radiogroup', choices: ['Yes','No','Maybe','Never'], isRequired: true, name: 'Test_01', title: 'Do you like ice cream?' }],showQuestionNumbers: 'off'}";
it works when removes quotes
json = { elements: [ {type: 'radiogroup', choices: ['Yes','No','Maybe','Never'], isRequired: true, name: 'Test_01', title: 'Do you like ice cream?' }],showQuestionNumbers: 'off'};
I have tried JSON.parse(json); it dosen't work, would anyone please suggest solution, please?

If you have JSON in a string, then you should do JSON.parse, not JSON.stringify.
Also, single quotes are invalid in JSON, so always use double-quotes for that.
// I fixed the JSON
var json = '{ elements: [ {type: "radiogroup", choices: ["Yes","No","Maybe","Never"], isRequired: true, name: "Test_01", title: "Do you like ice cream?" }],showQuestionNumbers: "off"}';
// The thing you would expect
var obj = JSON.parse(json);

Because you are trying to stringify a string no the object remove " " and it would become object and then try JSON.stringify and JSON.parse is not working because the data is not in proper JSON string format. For example:
var object = '{"e":"a"}';
Then use JSON.parse(object);
Which will convert your string in object.

Related

How to parse specific object in angular or javascript?

How are we going to parse following type of object in angular or javascript, maybe using for search loop or parsing?
I wanted to get the title value and assign it to title because as you can see the value of title is object:
{'title': 'Hey', 'instruction': 'Take a sad song a…75, 'sub_title': 'Jude', 'timelimit': '01:05:01'}
instead of "Hey" as you can see on the example (same also with the second object). Is there a way we can do that?
JSON array of objects format:
[
{
id:0,
title:"{'title': 'Hey', 'instruction': 'Take a sad song a…75, 'sub_title': 'Jude', 'timelimit': '01:05:01'}"
},
{
id:1,
title:"{'title': 'Assessment', 'instruction': 'Jude', 'cr…71, 'sub_title': 'Test', 'timelimit': '06:25:08'}"
}
]
Desired output:
[
{
id:0,
title:"Hey"
},
{
id:1,
title:"Assessment"
}
]
Make sure your have the correct format in json - double quotation marks inside and single outside.
Like this
'{"title": "Hey", "instruction": "Take a sad song a…75", "sub_title": "Jude", "timelimit": "01:05:01"}'
Then you can simply do.
let jsonString = '{"title": "Hey", "instruction": "Take a sad song a…75", "sub_title": "Jude", "timelimit": "01:05:01"}';
let title = JSON.parse(jsonString).title;
console.log(title);
var jsonObj = [
{
id:0,
title:"{'title': 'Hey', 'instruction': 'Take a sad song a…75, 'sub_title': 'Jude', 'timelimit': '01:05:01'}"
},
{
id:1,
title:"{'title': 'Assessment', 'instruction': 'Jude', 'cr…71, 'sub_title': 'Test', 'timelimit': '06:25:08'}"
}
];
var updatedJsonObj = jsonObj.map( obj => {
return {
...obj,
title: JSON.parse(obj.title).title
}
});
console.log(updatedJsonObj);
//updatedJsonObj will have your required format
Here we are doing following steps
Iterate over array
For each object, title field is not valid JSON. make it valid by using title.replace(/'/g, '"'). Then Parse JSON.
Then assign title of parsed JSON to title of object
Here is the code
arr = [
{
id:0,
title:"{'title': 'Hey', 'instruction': 'Take a sad song a…75', 'sub_title': 'Jude', 'timelimit': '01:05:01'}"
},
{
id:1,
title:"{'title': 'Assessment', 'instruction': 'Jude', 'sub_title': 'Test', 'timelimit': '06:25:08'}"
}
]
arr = arr.map((e)=> { e.title = JSON.parse(e.title.replace(/'/g, '"')).title; return e; })
// expected result is in arr
.
As others have stated your json is not valid but since you have mentioned that it is what you get from your backend and you cannot change it, I suggest treat your title as string and use string operations to get the desired value.
for example you can use the following to get ID and title
<div ng-repeat="item in data">
{{item.id}} -
{{item.title.split('\'')[3]}}
</div>
Demo

How to convert JSON string with attribute named with parenthesis to Typescript

I'm working with an Angular project. From a REST web service, I received the following JSON data:
{
records: [{
Contributor(Insertion): ["rec7wILrxxqg3R5MD"],
Country(Artist): ["E"],
ID: 70,
Museum: ["recFUvc63FW00oxvO"],
Name: ["Francisco "],
Notes: "1821-1823",
Pictures: [{id: "attEfUG32VAK2GYSt"}],
RecordID: "rec17E0Nisx3oRhhF",
Title: "Saturno che divora i suoi figli",
Year: 1823,
id: "rec17E0Nisx3oRhhF"}
]}
As you can see, there is a Contributor(Insertion) and Country(Artist) field. How can I parse it and convert in a Typescript attribute? Thank you in advance.
First your server needs to send you a valid JSON, JSON isn't just forgiving JavaScript Object
JSON keys must be strings wrapped in two quotations
export interface IMyInterface{
"records": [{
"key()": ["rec7wILrxxqg3R5MD"],
"key2": ["E"],
"key3": 70,
"key4": ["recFUvc63FW00oxvO"],
"key5": ["Francisco "],
"key6": "1821-1823",
"key7": [{"id": "attEfUG32VAK2GYSt"}],
"key8": "rec17E0Nisx3oRhhF",
"key9": "Saturno che divora i suoi figli",
"key10": 1823,
"key11": "rec17E0Nisx3oRhhF"}
]}
See more how to make good valid JSON
Then You need to handle the function keys as class and constructor for typing.
Pro-tip: automate your ts interface creation : http://json2ts.com/

JSON error when calling chart.draw from Google GeoChart library

I'm trying to use Google GeoChart library to display a map, and if I do it on a local HTML file or somewhere like JSFiddle, it works perfectly.
However, when I embed it in a JSP on my project and deploy it (using JBoss), calling chart.draw results in a JSON error:
Invalid JSON string: {":",":",":{":[",","]},":",":{":true}}
My complete Javascript method is as follows:
var data2 = google.visualization.arrayToDataTable([
[{label: 'Country', type: 'string'},
{label: 'description', type: 'string'},
{label: 'consistency', type: 'number'},
{type: 'string', role: 'tooltip'}],
['Canada', "CANADA", 2, "OK"],
['France', "FRANCE", 0, "KO"],
['USA', "USA", 1, "Other"]
]);
var options = {
displayMode: 'region',
backgroundColor: '#81d4fa',
colorAxis: {
colors: ['red', 'orange', 'green']
},
legend: 'none',
tooltip: {
showColorCode: true
}
};
var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(data2, options);
So it's clearly picking up the "structure" of the JSON object (two simple objects, another object with an array inside, another simple object, another object with an array inside), but for some reason is not picking up the content, except for the 'true' value, so it looks like a problem with quotes...
In any case, I have tried simple and double quotes, removing the quotes from the identifiers, reducing the options object to a simple
var options = {
"legend": "none"
};
... but to no avail. Everything results in a Invalid JSON string error (in this last case, a Invalid JSON string: {":"} error, since there is only one object).
Last note: if I just use
var options = {};
it shows the map (but with the default options).
Any ideas as to why is this happening and/or how to solve it?
Thanks!

Sending JSON object using rest

I am trying to create this:
[
{
"id":"1",
},
{
"id":"3",
},
{
"id":"5",
},
{
"id":"6",
},
{
"id":"9",
},
]
Person = {
"id" : Id
};
PersonArray.push(Person);
tempPersonJson['PersonList'] = JSON.stringify(PersonArray);
This is my output:
List = "[{\"id\":\"12\"},{\"id\":\"10\"},{\"id\":\"9\"},{\"id\":\"8\"},{\"id\":\"7\"},{\"id\":\"6\"},{\"id\":\"5\"},{\"id\":\"4\"},{\"id\":\"3\"},{\"id\":\"2\"},{\"id\":\"1\"},{\"id\":\"12\"},{\"id\":\"10\"},{\"id\":\"9\"},{\"id\":\"8\"},{\"id\":\"7\"},{\"id\":\"6\"},{\"id\":\"5\"},{\"id\":\"4\"},{\"id\":\"3\"},{\"id\":\"2\"},{\"id\":\"1\"}]";
API complains with this:
Call Body
Expected body: Content-Type is application/json but body is not a parseable JSONParse error on line 21: ...value": true },] ---------------------^ Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got ']'
Watchout for malformed JSON. Expected data media type ('null') does not match real media type ('application/json').
Update, JSON sent to server:
[{"id":"12"},{"id":"10"},{"id":"9"},{"id":"8"},{"id":"7"},{"id":"6"},{"id":"5"},{"id":"4"},{"id":"3"},{"id":"2"},{"id":"1"}]
So just taking a stab at it...>I created a jsfiddle for you....fixing some missing variables.
var Person = {
"id" : '1'
};
var PersonArray =[];
PersonArray.push(Person);
var tempPersonJson = [];
tempPersonJson['PersonList'] = JSON.stringify(PersonArray);
console.log('tp',tempPersonJson);
Working fiddle click here

Celleditor for object value Extjs4

I'm looking for a best solution how to do this.
What I have:
// model
Ext.define("User", {
extend: "Ext.data.Model",
fields: [
{name: "id", type: "int"},
{name: "name"},
{name: "description", type: "string"}
]
});
// store with data
var oStore = new Ext.data.Store({
model: "User",
data: [
{id: 1, name: {name:"John"}, description: "Fapfapfap"},
{id: 2, name: {name:"Danny"}, description: "Boobooboo"},
{id: 3, name: {name: "Tom"}, description: "Tralala"},
{id: 4, name: {name:"Jane"}, description: "Ololo"},
]
});
// and finally I have a grid panel
Ext.create("Ext.grid.Panel", {
columns: [
{dataIndex: "id", header:"ID"},
{
dataIndex: "name",
header: "Name",
renderer: function(value){return value.name;},
editor: "textfield"},
{dataIndex: "description", header: "Description", flex: 1, editor: "htmleditor"}
],
plugins: [new Ext.grid.plugin.CellEditing({clicksToEdit: 2})],
store: store,
renderTo: document.body
});​
When I doublecick on a cell I see [object] Object in editor's field, and when I enter valid value than I see empty cell in the grid.
So, the question is – how could I setup celleditor to get data not from record.name but from record.name.name?
You can override get and set methods on model, so the will support multi-level field names. Below is sample implementation.
Ext.define("User", {
extend: "Ext.data.Model",
fields: [
{name: "id", type: "int"},
{name: "name"},
{name: "description", type: "string"}
],
get: function(key) {
if (Ext.isString(key) && key.indexOf('.') !== -1) {
var parts = key.split('.');
var result = this.callParent([ parts[0] ]);
return result[parts[1]];
}
return this.callParent(arguments);
},
set: function(key, value) {
if (Ext.isString(key) && key.indexOf('.') !== -1) {
var parts = key.split('.');
var result = this.get(parts[0]);
result[parts[1]] = value;
this.callParent([ parts[0], result ]);
return;
}
this.callParent(arguments);
}
});
I am not sure if store detects change made to name.name field. If no, you should also probably mark record as dirty.
Working sample: http://jsfiddle.net/lolo/dHhbR/2/
The editor accepts whatever value is provided in the "dataIndex" field of the column. Since "name" is an object, that's what you're getting. After entering a name in the editor, value is equal to a string (not an object) and your renderer is trying to get the name property of the string.
The easiest way to fix this is to make the "name" field of your store a string instead of an object. However, I'm assuming there's a reason you want to do it this way.
The CellEditing plugin has three events it can listen for: beforeedit, edit, and validateedit. You can implement a beforeedit listener to get the "name" object from the column, then get the "name" property of that object and fill the editor with that value. Then on validateedit, get the value from the editor and set the "name" property of the "name" object in the record with that value.
For quick reference, here's the event definition: CellEditing events
An easier way is to modify your User Model object to map the "name" property differently:
{name: "name", mapping:'name.name'}
then everything else stays the same.

Categories