I have a JSON object that looks like this:
var obj = {
"selection":[
{
"author":"John Doe",
"articles":[
"Article One",
"Article Two"
]
}
]
}
I want to pass this object to Django to render a view that displays 'Article One' and 'Article Two' upon render. I first serialize the JSON object so that it can be appended to a URL; I use $.param(obj) for serialization. Now the JSON object looks something like this:
"selection%5B0%5D%5Bauthor%5D=John+Doe&selection%5B0%5D%5Barticles%5D%5B%5D=Article+One&selection%5B0%5D%5Barticles%5D%5B%5D=Article+Two"
Now I can append this to a path and use window.open(url) the view will handle everything else. On the Django end, I was surprised to see that the structure of the JSON object has changed to this:
"selection[0][author]=John+Doe&selection[0][articles][]=Article+One&selection[0][articles][]=Article+Two"
I want to be able to use the JSON object as a dict e.g.:
obj = request.GET.get('selection')
obj = json.loads(obj)
print(obj[0].author)
...
How should I handle this JSON structure on the Django side of things?
You are not properly serializing the object to JSON, even if you say you do. The correct way would be to use JSON.stringify(), as #dunder states.
Than you parse it back to an object with JSON.parse(strignifiedJson).
var obj = {
"selection":[
{
"author":"John Doe",
"articles":[
"Article One",
"Article Two"
]
}
]
}
// Stringify and encode
var objAsParam = encodeURIComponent(JSON.stringify(obj));
// Send as a param, for example like http://example.com?obj=YourStringifiedObject...
// Parse it back:
var parsedObj = JSON.parse(decodeURIComponent(objAsParam));
Related
testDetails.map(function(data){
let JsonData={
title: data["title"],
url: data["url"],
firstName: data["username"],
work:[{workid:data["workid"].slice(","), workname: "tester"}],
employee: [{employee_id: data["employee_id"].slice(","), employee_desk:"custom"}]
}
})
so my above json output look like this
{
"title":"01"
"url":"employe#url.com",
"firstName":"employee name",
"work":[{"workid":"9371", "workname": "tester"}],
"employee":[{"employee_id":"weh34",employee_desk:"custom"}]
}
and another JSON object where data look like this
let data={
"031w":"ewid3728e",
"9371":"emp_01",
"weh34":"work_place01"
}
The workid and employee id with the JsonData I want to replace with the value which is present inside the data json so my data which is look like this
"work":[{"workid":"9371", "workname": "tester"}],
"employee":[{"employee_id":"weh34",employee_desk:"custom"}]
needed to be look like this
"work":[{"workid":"work_place01", "workname": "tester"}],
"employee":[{"employee_id":"emp_01",employee_desk:"custom"}]
I am trying to replace the code manually like this
work:[{workid:data.weh34, workname: "tester"}],
employee: [{employee_id: data.9371, employee_desk:"custom"}]
but data["workid"].slice(",") and data["employee_id"].slice(",") always get changed so I want to match both the json and fetch the value and place it in my JsonData
Just use the value you got from testDetails as the index in the data object to get the corresponding value.
You need to use a different variable from data as the parameter to the mapping function so you can refer to the external variable data. I changed it to d below.
testDetails.map(d => ({
title: d["title"],
url: d["url"],
firstName: d["username"],
work: [{
workid: data[d["workid"].slice(",")],
workname: "tester"
}],
employee: [{
employee_id: data[d["employee_id"].slice(",")],
employee_desk: "custom"
}]
}));
I want to model the following information into json but am unable to do so.
The server sends result of an operation to the client using the following model
class Result (result:string, additional-info:string)
additional-info could contain a json or a string depending on the use case. Thus its type is String. When I need to send a json in it, I simply send a string with a valid json syntax and I suppose the the Angular client would be able to convert the string into a json using JSON.parse.
The json I want to send to the client looks like
{
"result": "success",
"additional-info": {
"list ": [{
"tag": "sometag",
"description": "some description"
}]
}
}
I checked on jsonlint (https://jsonlint.com/) that the structure is correct.
On the client side (Angular), I am handing the message as follows:
getQuestions(some args){
console.log('response from server:',res)
console.log('response body',res.body)
let jsonResponse:ServerResponseAPI = res.body //should contain result and additional info
console.log("result: "+jsonResponse.result+", additional info:"+jsonResponse.additionalInformation)
let jsonList:string = jsonResponse.additionalInformation
console.log("jsonQuestionList: "+jsonList)
let information:Information = JSON.parse(jsonList)
console.log("information:"+information)
});
}
ServerResponseAPI is defined as
export class ServerResponseAPI{
constructor ( public result:string,
public additionalInformation:string){}
}
When I execute the code, I see the following prints on browser's console but I see that error that additional-info is not define.
response body {result: "success", additional-info: "{"list ": [{"tag": "sometag", "description": "some description"}]}"}
list-management.service.ts:46 result: success, additional info:undefined
I can see that the body contains result and additional-info but after casting the body to ServerResponseAPI, I see that result is success but additional-info is undefined.
in res.body, javascript creates an object
{
"result": "success",
"additional-info": {
"list ": [{
"tag": "sometag",
"description": "some description"
}]
}
}
The object has two keys - result and additional-info. Lets call it Object1
I assign it to an object which has keys result and additionalInfo. Note the difference in naming convention in additionalInfo. In javascript, names of variables are case sensitive, so the above two are different. Lets call this object2
Now result from object1 gets assigned to result from object2 because the keys match (same name result)
additional-info becomes a new key in the object2
additionalInfo key of object2 stays undefined as no key from object1 maps to additionalInfo
To solve the issue, I had to create a additional-info key ServerResponseAPI (alternatively I could have also changed my JSON property name to additionalInfo but I didn't want to change that). This is done in Angular as
export class ServerResponseAPI{
'additional-info':string;
constructor ( public result:string,
public additionalInformation:string){
this['additional-info'] = additionalInformation;
}
}
In my code, I now access the keys as
let jsonResponse:ServerResponseAPI = res.body //contains result and additional info
console.log("result: "+jsonResponse.result+", additional info:"+jsonResponse['additional-info'])
let jsonQuestionList:string = jsonResponse['additional-info']
I am writing to a json file in casperjs and am trying to add new objects to it.
json file looks like
{ "visited": [
{
"id": "258b5ee8-9538-4480-8109-58afe741dc2f",
"url": "https://................"
},
{
"id": "5304de97-a970-48f2-9d3b-a750bad5416c",
"url": "https://.............."
},
{
"id": "0fc7a072-7e94-46d6-b38c-9c7aedbdaded",
"url": "https://................."
}]}
The code to add to the array is
var data;
if (fs.isFile(FILENAME)) {
data = fs.read(FILENAME);
} else {
data = JSON.stringify({ 'visited': [] });
}
var json = JSON.parse(data);
json.visited.push(visiteddata);
data = JSON.stringify(json, null, '\n');
fs.write(FILENAME, data, "a");
This is starting off by adding an new { "visited" : [ ] } array with first couple of objects, below the existing { "visited" : [ ] } array and subsequently the script breaks because the json array is no longer valid json.
Can anybody point me in the right direction. Thank you in advance.
You have a JSON file containing some data.
You:
Read that data
Modify that data
Append the modified version of that data to the original file
This means the file now has the original data and then, immediately after it, a near identical copy with a little bit added.
You don't need the original. You only need the new version.
You need to write to the file instead of appending to it.
Change the 'a' flag to 'w'.
So in ASP.NET MVC I have a Controller action somewhat like this:
public JsonResult People()
{
var people = db.People.ToList();
return Json(people);
}
and when ajaxed this will return something like this:
[
{
"ID": 1,
"Name": "John Smith"
},
{
"ID": 2,
"Name": "Daryl Jackson"
}
]
However, what I'm looking for is not a JSON array of the records as shown above, but more a JSON object where the IDs of each record is the key and then the record nested as the value, like so:
{
1: {
"Name": "John Smith"
},
2: {
"Name": "Daryl Jackson"
}
}
My initial thought would be to create a Dictionary in C# similar to this structure and pass it into Json() however the method does not know how to handle Dictionary objects.
Is there a way to achieve this kind of structure in C#? Currently I'm having to resort to restructuring it on the client-side or using loops to find a record with the ID I'm searching for. It'd be nicer if I could just get the record by ID in Javascript. Am I going about this all wrong? I'm new to the ASP.NET MVC environment.
Any suggestions would be greatly appreciated. Thank you :)
You can use the ToDictionary() extension method.
public ActionResult People()
{
var peopleDictionary = db.People
.Select(x=> new { Id = x.Id, Name= x.FirstName})
.ToDictionary(d => d.Id.ToString(), p => p);
return Json(peopleDictionary, JsonRequestBehavior.AllowGet);
}
Assuming your People table has an Id and FirstName column, this code will return a json dictionary like this from your table data
{ "101" : {"Id":101,"Name":"John"},"102":{"Id":102,"Name":"Darryl"} }
Using the Json metod, You cannot serialize a dictionary where the dictionary key is of type int, so you need to explicitly convert your int value to a string.
If you want to get a specific user from the a userId, you can use the dictionary style syntax yourJsObject[key]
var url="PutRelativeUrlToReportScoreHere";
$.getJSON(url, function(data) {
console.log(data);
//Get the User with Key 102
console.log(data[102]);
});
I have a json url that returns data in the format
{
"photos" : [
{
"id": 1, "image":"https://path/to/my/image/1.jpg"
},
{
"id": 2, "image":"https://path/to/my/image/2.jpg"
}
]
}
I'm using the json in a javascript function, and need to manipulate it to remove the root key. i.e. I want something that looks like
[
{
"id": 1, "image":"https://path/to/my/image/1.jpg"
},
{
"id": 2, "image":"https://path/to/my/image/2.jpg"
}
]
I've been hacking around with various approaches, and have referred to several similar posts on SO, but nothing seems to work. The following seems like it should.
var url = 'http://path/to/my/json/feed.json';
var jsonSource = $.getJSON( url );
var jsonParsed = $.parseJSON(jsonSource);
var jsonFeed = jsonParsed.photos
What am I doing wrong?
A couple of issues there.
That's invalid JSON, in two different ways. A) The : after "photos" means that it's a property initializer, but it's inside an array ([...]) when it should be inside an object ({...}). B) There are extra " characters in front of the images keys. So the first thing is to fix that.
You're trying to use the return value of $.getJSON as though it were a string containing the JSON text. But $.getJSON returns a jqXHR object. You need to give it a success callback. That callback will be called with an object graph, the JSON is automatically parsed for you.
Assuming the JSON is fixed to look like this:
{
"photos": [
{
"id": 1,
"image": "https://path/to/my/image/1.jpg"
},
{
"id": 2,
"image": "https://path/to/my/image/2.jpg"
}
]
}
Then:
$.getJSON(url, function(data) {
var photos = data.photos;
// `photos` now refers to the array of photos
});