Unable to access JSON data from Javascript - javascript

I am passing the following from my Django back-end to my front-end in order to dynamically build a form :
{
"access_key": "93ec6137de00eacee6f8",
"profile_id": "7851E15D64",
"transaction_uuid": "c878c7e6db5657526",
}
Within the browser console, if I pass :
MyJSON = {
"access_key": "93ec6137de00eacee6f8",
"profile_id": "7851E15D64",
"transaction_uuid": "c878c7e6db5657526",
}
Then I can access each value properly, for example, MyJSON.access_key returns 93ec6137de00eacee6f8 perfectly within the console.
However, from my Javascript, I am unable to access any of those values as i get an "undefined".
var obj = JSON.parse(MyJSON)
console.log(obj) // returns the whole JSON String
console.log(typeof(obj)) // returns 'string'
alert(obj[0]) // returns "{", the very first character of the 'string'
alert(obj.access_key) // returns "undefined".
- How can access each Key and Value from MyJSON from my javascript? (not JQuery)
Note that I have reviewed many similar article but I must be missing the obvious ...
Hope you can assist !
Thanks in advance.
EDIT :
I have a list of Fields and a list of Values which i then merge into the below (pass the JSON Validator on https://jsonlint.com/):
{'access_key': '93ec6137d70aada23400eacee6f8', 'profile_id': '7851E53E-96BB-4D4-BD5-0FE61CC15D64', 'transaction_uuid': '00939a90-db7b-41cb-af45-669ec5cc69e8', 'signed_field_names': 'bill_to_forename,bill_to_surname,bill_to_email,bill_to_phone,bill_to_address_line1,bill_to_address_city,bill_to_address_postal_code,bill_to_address_country,transaction_type,reference_number,payment_method,amount,currency,locale,card_type,card_number,card_expiry_date', 'unsigned_field_names': 'card_type,card_number,card_expiry_date', 'signed_date_time': '2021-05-23T16:20:17Z', 'bill_to_forename': 'John', 'bill_to_surname': 'Doe', 'bill_to_email': 'null#cfgfg.com', 'bill_to_phone': '07922889582', 'bill_to_address_line1': '123 Random Street', 'bill_to_address_city': 'London', 'bill_to_address_postal_code': 'RG1T3X', 'bill_to_address_country': 'GB', 'transaction_type': 'sale', 'reference_number': 'o6yejf', 'payment_method': 'card', 'amount': '100', 'currency': 'USD', 'locale': 'en', 'card_type': '001', 'card_number': '4456530000001096', 'card_expiry_date': '12-2026', 'signature': 'Un5gNYB5qZaRazzCDWqrdZuNkTRARIcfAt9aF2a1wbY='}
Back-end Code
FieldList = ['access_key', 'profile_id', 'transaction_uuid', 'signed_field_names', 'unsigned_field_names', 'signed_date_time', 'bill_to_forename', 'bill_to_surname', 'bill_to_email', 'bill_to_phone', 'bill_to_address_line1', 'bill_to_address_city', 'bill_to_address_postal_code', 'bill_to_address_country', 'transaction_type', 'reference_number', 'payment_method', 'amount', 'currency', 'locale', 'card_type', 'card_number', 'card_expiry_date', 'signature']
ValueList = ['93ec6137d0aada23400eacee6f8', '7851E53E-96BB-4DF4-BD55-0FE61CC15D64', 'c4fe96b0-063f-4b94-a6a5-2137bb796bd9', 'bill_to_forename,bill_to_surname,bill_to_email,bill_to_phone,bill_to_address_line1,bill_to_address_city,bill_to_address_postal_code,bill_to_address_country,transaction_type,reference_number,payment_method,amount,currency,locale,card_type,card_number,card_expiry_date', 'card_type,card_number,card_expiry_date', '2021-05-23T16:27:24Z', 'John', 'Doe', 'null#cyrce.com', '07922889582', '123 Random Street', 'London', 'RG1T3X', 'GB', 'sale', 'xl42fn', 'card', '100', 'USD', 'en', '001', '4456530000001096', '12-2026', 'vvb73h0GUpzUrvoG9VDaMc3vQRV5GsL4QTATc7IrrPA=']
NewFormat = dict(zip(FieldList, ValueList))
MyJSON = json.dumps(NewFormat, indent=4)
return JsonResponse(MyJSON, safe=False)
Apologies for the large amount of data.
I am somehow forced to use "safe=False" in my Python back-end otherwise I end up with :
Traceback (most recent call last):
File "/home/pi/.local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner
response = get_response(request)
File "/home/pi/.local/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/pi/Documents/Droplet/Droplet/Harness/sasop2.py", line 543, in signsasop
return JsonResponse(FinalJSONObject)
File "/home/pi/.local/lib/python3.7/site-packages/django/http/response.py", line 561, in __init__
'In order to allow non-dict objects to be serialized set the '
TypeError: In order to allow non-dict objects to be serialized set the safe parameter to False.
Since I am passing safe=False, is that why my front-end does not get the MyJSON as... JSON?
Would this be the root cause of the issue?
Front-End Sample :
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// Print received data from server
console.log('%c Processed Data \n',
'background: #000000; color: #FFFFFF; font-size: 30px'
,xhr.response);
// Dynamically create the ReconstructedForm
RawProcessedData = xhr.response
console.log(RawProcessedData)
// Convert to JSON
var obj = JSON.parse(RawProcessedData)
console.log(obj)
console.log(typeof(obj))
alert(obj[0])
alert(obj.access_key)

Thanks a lot for your quick input !
As per deceze's answer, I was essentially double parsing both in the back and front end for no reasons.
Removing the json.dumps from the backend allows the JSON object to be passed and managed in the front end without issue.

I have the same issue when i started developing on Django. If you need to pass dictionarys from django to javascripts, the best thing to do is just using django rest framework. It serialize ( in other words, it transform any data into a dictionary/json ) any given data from a model.
But if you want to make this without Django Rest, you should use fetch on javascript. This fetch ( also called as a "Promise") communicate with the backend ( in this case, Django ) and it GET or POST data from the frontend. I will give you an example.
Supose you have this on views.py:
from django.http.response import JsonResponse
def getJSON(request):
MyJSON = {
"access_key": "93ec6137de00eacee6f8",
"profile_id": "7851E15D64",
"transaction_uuid": "c878c7e6db5657526",
}
return JsonResponse(MyJSON)
And the you can link that to the urls.py like this:
urlpatterns = [
path('get-json', views.getJSON, name="get-json")
]
Then you can GET that JSON by doing this on your javascript:
function getDataJson(){
let url = 'get-json'
fetch(url,{
headers: {
"Content-type": "application/json",
},
})
.then(response => response.json())
.then(data=> console.log(data))
}
This will console log your data.

Related

Sending True/False from python api call

i dont know if this is a stupid question but ive made a script that is making a api put call using requests in python. The data im trying to send contains a boolean value. So i have my script like this
import requests
data = {
'name': 'John',
'lastname': "Doe",
'email': "jd#gmail.com",
'is_staff' : True
}
url = 'http://api.url/user/'
response = requests.put(
url, data=data, verify=True, allow_redirects=False)
print(response)
But this gives me a 400 request error.
Then i thought that the problem was with the api call but when i remove the is_staff data.
data = {
'name': 'John',
'lastname': "Doe",
'email': "jd#gmail.com",
}
I get a 200 status code. My inutution is telling me that the api doesnt know what the boolean value from python is. But i could be wrong. Any ideas?
You need to JSON encode your string or rather 'serialize'.
Serialize obj to a JSON formatted str using this conversion table. If ensure_ascii is false, the result may contain non-ASCII characters and the return value may be a unicode instance.
Source
import requests
import json
data = {
'name': 'John',
'lastname': "Doe",
'email': "jd#gmail.com",
'is_staff' : True
}
url = 'http://api.url/user/'
headers = {'content-type': 'application/json'}
response = requests.put(url, data=json.dumps(data), headers=headers, verify=True, allow_redirects=False)
print(response)
The requests library takes the data dict and turns it into the request body, the request body is not a dict but a string containing the keys and values. In this case it turns it into the key1=value1&key2=value2 form.
You can view the request body the requests library is sending by:
response.request.body
It returns
'name=John&lastname=Doe&email=jd%40gmail.com&is_staff=True'
In this case the boolean you are sending is turned into "True" or "False". The problem could be that the webserver is expecting a "true" or "false" instead but it depends on the server.
Try:
data = {
'name': 'John',
'lastname': "Doe",
'email': "jd#gmail.com",
'is_staff' : "true"
}
Or the dynamic:
is_staff = True
data = {
'name': "John",
'lastname': "Doe",
'email': "jd#gmail.com",
'is_staff' : str(is_staff).lower()
}

Is it possible to update js file using php command?

I have script.js file. and it has following array
script.js
'COntent': function() {
var contentFacts = {
blocks: {
'block1': {
name: 'yleow',
title: 'H2',
type: 'content'
}
}
};
}
},
I tried like this in my php , but it did not work :(
$lines = file($path.'/script.js');
$lines[64] = "'block2': {name: 'yleow',title: 'H2',type: 'content'}"
file_put_contents($path.'/script.js', implode($lines));
I want to add another element call block2 for this array. How can i update my script.js file function using php?
Is it possible using file_put_contents? please advice
JavaScript is a very poor substitute for a database or any other structured data format. In this case even more because you are trying to inject content into source code.
What you probably want is some form of structured data outside of your code for example a JSON file or an SQLite database.
PHP does support parsing from and serializing to JSON:
json_decode
json_encode
Possible solution
Put the contentFacts into a seperate JSON file
{
"blocks": {
"block1": {
name: 'yleow',
title: 'H2',
type: 'content'
}
}
}
Manipulate JSON with PHP
$json = file($path.'/blocks.json');
$blocks = json_decode($json, true);
$blocks['block2'] = array(
'name' => 'blue',
'title' => 'h3',
'type' => 'content'
);
Write back to JSON file
$adapted_json = json_encode($blocks);
file_put_contents($path.'/blocks.json');
Now you need to get this into your JavaScript part, I assume on the client. You can do this by requesting it from the server:
const contentPromise = fetch('/path/to/blocks.json');
contentPromise.then((blocks) => {
// Do something with those blocks. (render them to the page?)
});

Malformed request when creating billing plan

So I a using the node paypal-rest-sdk module and I'm trying to create a billing plan. Using the documentation here I made this JSON:
const billingPlanAttributes = {
name: 'Subscription',
description: 'Monthly subscription plan',
type: 'INFINITE',
payment_definitions: [{
name: 'Regular monthly infinite payments',
type: 'REGULAR',
frequency_interval: '1',
frequency: 'MONTH',
cycles: '0',
amount: {
currency: 'USD',
amount: '4.99',
},
}],
merchant_preferences: {
cancel_url: 'http://localhost:3000/subscribe/cancel',
return_url: 'http://localhost:3000/subscribe/return',
auto_bill_amount: 'YES',
},
};
But when using the paypal.billingPlan.create(... function I get the error 'MALFORMED_REQUEST', 'Incoming JSON request does not map to API request'. So I guess my JSON is not in the correct format or I'm missing something that is need.
The documentation has a charge_models key but it does not mention that it is required unlike other keys.
If you can point me in the right direction that would be great.
Edit: changed the return url and cancel url to include the full domain but still same error.
There could be more to this, but I noticed one thing wrong with your JSON. Remove commas for items last in a list. After 'amount' and 'merchant_preferences'. JSON is picky.
late answer, I know, but ran in exactly the same issue than you.
In the create function of the billing plan
public function create($apiContext = null, $restCall = null)
{
$payLoad = $this->toJSON();
$json = self::executeCall(
"/v1/payments/billing-plans/",
"POST",
$payLoad,
null,
$apiContext,
$restCall
);
$this->fromJson($json);
return $this;
}
I found out, that the toJSON method always returned false. Why the hell!?!
I did the same as you did and copied the complete sample code into my code. Then it worked as expected. Now I checked, what the difference was in to my code.
I realized, that I used an umlauts (ä,ü,ö) in the name and description of the billing plan. I changed the umlauts to
'ä' => 'ae',
'ö' => 'oe'
'ü' => 'ue'
Then it worked fine! Maybe someone else is running in this issue, too.

Send JSON list from Javascript to Django Backend and parsing it properly

I am trying to send a POST request to Django but I am not being able retrieve a json list. I can get the backend to retrieve the items (json objects) from the list but these objects seems unreadable.
Could someone please check my procedure and the results at the end of this thread? I am running out of options here =/
Step 1: Creating the JSON list:
google_news_articles = []
Step 2: Populating the JSON list:
for (each_checkbox in self.coverage_report_google_news_table.checked_rows){
var each_article = $(self.coverage_report_google_news_table.checked_rows[each_checkbox]).parents('tr');
google_news_articles.push({
date: each_article.find('.date').text(),
outlet_domain: strip(each_article.find('.outlet_domain').text()),
title: each_article.find('.title').text(),
link: each_article.find('.title').attr('href')
});
}
Step 3: Making a POST Request:
$.post('/google_news_unsafe_add/',{
'google_news_articles[]': google_news_articles,
'csrfmiddlewaretoken': $('[name="csrfmiddlewaretoken"]').val()
},function(result){
if(result.result=='ok'){
$('#save-status').html("Saved");
}else{
$('#save-status').html("An Error Occurred");
}
});
Step 4: Handling it from the Backend:
def google_news_unsafe_add_view(request):
print '!!!'
print request.POST
print '!!!'
print '\\\\\\'
print request.POST.getlist('google_news_articles[]')
print '\\\\\\'
return
Results: Terminal Prints:
!!!
<QueryDict: {u'csrfmiddlewaretoken': [u'nm5NAJyHEvoiFOThSrffU1pETcrQ7oa2'], u'google_news_articles[]': [u'[object Object]', u'[object Object]']}>
!!!
\\\
[u'[object Object]', u'[object Object]']
\\\
All I have is this [u'[object Object]', u'[object Object]'] list and when I try to parse the list, I get:
json.loads(request.POST.getlist('google_news_articles[]'))
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
TypeError: expected string or buffer
And when trying to parse the objects, I get:
print json.loads(each_json)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 383, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
Any hints?
Thanks to Two-Bit Alchemist's comment I realized I should not send a pure JSON object but a serialized JSON object instead.
So I replaced this:
google_news_articles.push({
date: each_article.find('.date').text(),
outlet_domain: strip(each_article.find('.outlet_domain').text()),
title: each_article.find('.title').text(),
link: each_article.find('.title').attr('href')
});
for this:
google_news_articles.push(JSON.stringify({
date: each_article.find('.date').text(),
outlet_domain: strip(each_article.find('.outlet_domain').text()),
title: each_article.find('.title').text(),
link: each_article.find('.title').attr('href')
}));
And things are now working smoothly =)

jQuery and my passed data to ajax is not at all what I intend

I am not sure what is going on. I've done exhausted searching for an answer. I thought it was processData but the ajax won't fire off in that case. I can't for the life of me figure out what is going on.
I am trying to send data via POST, ajax.
Because of how my data is set up, in page, I can actually create a hash and push it into an array. So I have something like.
The data I am forming looks like this:
in my init func, I set up some vars.
this.dataHolder = [];
in a method in my plugin:
_acceptData:function(){
var item = {};
item[this.schema.itemId] =
{
"Color" : this.schema.color,
"Size" : this.schema.size,
"Cost" : this.schema.cost
}
return item;
},
basically I have some other methods and such, but the jist is that that data structure above gets put into: this.dataHolder
when I dump the data, looks like it should. Various console.logs thruout the code shows me the data is well formed etc.. BUT when I pass it into the ajax data.. it does wonky things.
When I have my ajax.. ala:
var self = this;
.ajax({
type: "POST",
data : {matchedItems : self.dataHolder},
dataType: json,
url : /some/path/
I tried soo many different things, and in all cases the data is either undefined (when I Post it) OR its in a weird format, like: (in logs)
$VAR1 = {
'matchedItems[0][itemid1][Color]' => 'Blue',
'matchedItems[0][itemid1][Size]' => '11',
'matchedItems[0][itemid1][Cost]' => '33.90',
'matchedItems[1][itemid2][Color][]' => 'Silver',
'matchedItems[1][itemid2][Size]' => '13',
'matchedItems[1][itemid2][Cost]' => '44',
'matchedItems[2][itemid3][Color][]' => 'Red',
'matchedItems[2][itemid3][Size]' => '9',
'matchedItems[2][itemid3][Cost]' => '23'
};
or different permutations
data : MatchedItems : {self.dataHolder}
or
data : {MatchedItems : {self.dataHolder}}
etc.. doesn't matter, the POST always gets some really odd formatting.
This is the way it should look when I send it and how they receive it.
matchedIeds = {
itemId1 :
{
Color : Red,
Size : 11,
Cost : 44
},
itemId2 :
{
Color : Blue,
Size : 8,
Cost : 12
},
itemId3 :
{
Color : Blue,
Size : 19,
Cost : 88.09
}
}
I mean, I am setting up my data like that so I can't see what is wrong.
Note: I tried processData : false, but that didn't help at all.
EDIT:
Here is the code console.log'd out write before I pass it into the .ajax method.
Console.log
[Object { itemid1={...}}, Object { itemid2={...}}, Object { itemid3={...}}]
Here it is in the params of the post:
jquery.js (line 641)
POST http://www.myurl/to/test
200 OK
79ms
jquery.js (line 7829)
HeadersPostResponseJSONCookies
Parametersapplication/x-www-form-urlencoded
undefined undefined
undefined undefined
undefined undefined

Categories

Resources