简体   繁体   English

无法从 Javascript 访问 JSON 数据

[英]Unable to access JSON data from Javascript

I am passing the following from my Django back-end to my front-end in order to dynamically build a form:我将以下内容从我的 Django 后端传递到我的前端,以便动态构建表单:

{
    "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.然后我可以正确访问每个值,例如 MyJSON.access_key 在控制台中完美返回 93ec6137de00eacee6f8 。

However, from my Javascript, I am unable to access any of those values as i get an "undefined".但是,从我的 Javascript 中,我无法访问这些值中的任何一个,因为我得到一个“未定义”。

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? - 如何从我的 javascript 访问 MyJSON 中的每个键和值? (not JQuery) (不是 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/ ):我有一个字段列表和一个值列表,然后我将它们合并到下面(通过https://jsonlint.com/上的 JSON 验证器):

   {'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:我不知何故被迫在我的 Python 后端使用“safe=False”,否则我最终会得到:

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?既然我通过了 safe=False,这就是为什么我的前端没有将 MyJSON 设为... 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.根据 deceze 的回答,我基本上无缘无故地在后端和前端进行双重解析。

Removing the json.dumps from the backend allows the JSON object to be passed and managed in the front end without issue.从后端删除 json.dumps 允许 JSON object 在前端顺利通过和管理。

I have the same issue when i started developing on Django.当我开始在 Django 上开发时,我遇到了同样的问题。 If you need to pass dictionarys from django to javascripts, the best thing to do is just using django rest framework .如果您需要将字典从 django 传递到 javascripts,最好的办法就是使用django rest 框架 It serialize ( in other words, it transform any data into a dictionary/json ) any given data from a model.它序列化(换句话说,它将任何数据转换为字典/json)来自 model 的任何给定数据。 But if you want to make this without Django Rest, you should use fetch on javascript.但是,如果您想在没有 Django Rest 的情况下进行此操作,则应在 javascript 上使用fetch This fetch ( also called as a " Promise ") communicate with the backend ( in this case, Django ) and it GET or POST data from the frontend.此获取(也称为“ Promise ”)与后端(在本例中为 Django )通信,并从前端获取或发布数据。 I will give you an example.我会给你一个例子。

Supose you have this on views.py :假设你在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:您可以将其链接到urls.py ,如下所示:

urlpatterns = [
    path('get-json', views.getJSON, name="get-json")
]

Then you can GET that JSON by doing this on your javascript :然后,您可以通过在 javascript 上执行此操作来获取JSON

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.这将控制台记录您的数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM