簡體   English   中英

無法從 Javascript 訪問 JSON 數據

[英]Unable to access JSON data from Javascript

我將以下內容從我的 Django 后端傳遞到我的前端,以便動態構建表單:

{
    "access_key": "93ec6137de00eacee6f8",
    "profile_id": "7851E15D64",
    "transaction_uuid": "c878c7e6db5657526",
}

在瀏覽器控制台中,如果我通過:

MyJSON = {
    "access_key": "93ec6137de00eacee6f8",
    "profile_id": "7851E15D64",
    "transaction_uuid": "c878c7e6db5657526",
    }

然后我可以正確訪問每個值,例如 MyJSON.access_key 在控制台中完美返回 93ec6137de00eacee6f8 。

但是,從我的 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".

- 如何從我的 javascript 訪問 MyJSON 中的每個鍵和值? (不是 JQuery)

請注意,我已經查看了許多類似的文章,但我一定錯過了明顯的......

希望您能提供幫助!

提前致謝。

編輯:

我有一個字段列表和一個值列表,然后我將它們合並到下面(通過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='}

后端代碼

    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)

為大量數據道歉。

我不知何故被迫在我的 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.

既然我通過了 safe=False,這就是為什么我的前端沒有將 MyJSON 設為... JSON?

這會是問題的根本原因嗎?

前端示例:

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) 

非常感謝您的快速輸入!

根據 deceze 的回答,我基本上無緣無故地在后端和前端進行雙重解析。

從后端刪除 json.dumps 允許 JSON object 在前端順利通過和管理。

當我開始在 Django 上開發時,我遇到了同樣的問題。 如果您需要將字典從 django 傳遞到 javascripts,最好的辦法就是使用django rest 框架 它序列化(換句話說,它將任何數據轉換為字典/json)來自 model 的任何給定數據。 但是,如果您想在沒有 Django Rest 的情況下進行此操作,則應在 javascript 上使用fetch 此獲取(也稱為“ Promise ”)與后端(在本例中為 Django )通信,並從前端獲取或發布數據。 我會給你一個例子。

假設你在views.py上有這個:

from django.http.response import JsonResponse

def getJSON(request):
    MyJSON = {
        "access_key": "93ec6137de00eacee6f8",
        "profile_id": "7851E15D64",
        "transaction_uuid": "c878c7e6db5657526",
    }

    return JsonResponse(MyJSON)

您可以將其鏈接到urls.py ,如下所示:

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

然后,您可以通過在 javascript 上執行此操作來獲取JSON

function getDataJson(){
    let url = 'get-json'

    fetch(url,{
        headers: {
            "Content-type": "application/json",
          },
    })
    .then(response => response.json())
    .then(data=> console.log(data))
}

這將控制台記錄您的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM