Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/376.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
无法从Javascript访问JSON数据_Javascript_Json - Fatal编程技术网

无法从Javascript访问JSON数据

无法从Javascript访问JSON数据,javascript,json,Javascript,Json,为了动态构建表单,我将以下内容从Django后端传递到前端: { "access_key": "93ec6137de00eacee6f8", "profile_id": "7851E15D64", "transaction_uuid": "c878c7e6db5657526", } 在浏览器控制台中,如果我通过: MyJSON = { &quo

为了动态构建表单,我将以下内容从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中,我无法访问这些值中的任何一个,因为我得到了一个“未定义的”

-如何从我的javascript访问MyJSON中的每个键和值?(不是JQuery)

请注意,我已经看过许多类似的文章,但我必须错过明显的

希望你能帮忙

提前谢谢

编辑:

我有一个字段列表和一个值列表,然后将它们合并到下面(传递JSON验证程序):

后端代码

    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对象而不会出现问题。

我开始在Django上开发时也遇到了同样的问题。如果需要将字典从django传递到javascripts,最好的方法就是使用django rest framework。它序列化(换句话说,它将任何数据转换为字典/json)模型中的任何给定数据。 但是如果您想在没有Django Rest的情况下实现这一点,那么应该在javascript上使用fetch。此获取(也称为“承诺””)与后端(在本例中为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)
您可以将其链接到url.py,如下所示:

urlpatterns=[
路径('get-json',views.getJSON,name=“get-json”)
]
然后,您可以通过在javascript上执行此操作来获取JSON:

from django.http.response import JsonResponse

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

    return JsonResponse(MyJSON)
函数getDataJson(){ 让url='get json' 获取(url{ 标题:{ “内容类型”:“应用程序/json”, }, }) .then(response=>response.json()) .then(数据=>console.log(数据)) }
这将控制台记录您的数据。

您的
MyJSON
是否实际有效?你能把它寄出去吗?如果它不是双引号或其他有效的JSON,而是一个字符串,它将只返回该字符串。您提供的代码不会给出您所说的结果
MyJSON
是一个对象,而不是JSON。您不能将其解析为JSON。在您尝试解析之前或之后,它都不是字符串。@Quentin我已经添加了我的后端和前端代码示例。希望这会有所帮助。您需要对JSON进行两次编码,因此还需要对其进行两次解析……当然,更好的方法是:删除多余的手册
JSON。dumps
MyJSON
不是JSON数据
JSON.parse(MyJSON)
没有意义。您似乎混淆了JSON与JavaScript对象和Python字典,因为它们看起来很相似。
from django.http.response import JsonResponse

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

    return JsonResponse(MyJSON)