繁体   English   中英

Javascript数据格式,这个是JSON吗?

[英]Javascript Data Format, Is This JSON?

我使用的一些 jquery 插件需要这种格式的数据作为其输入类型

[
{image : '1.jpg', title : 'Title', url : '', age : 24, location : 'US', name : 'John', description : 'Long Text'},  
{image : '1.jpg', title : 'Title', url : '', age : 24, location : 'US', name : 'John', description : 'Long Text'}, 
{image : '1.jpg', title : 'Title', url : '', age : 24, location : 'US', name : 'John', description : 'Long Text'}
]

我的问题是,这种数据是什么以及如何创建它? 这还是 JSON 吗? 因为当我尝试使用 PHP 传递 json_encoded 数组并使用 jquery 获取它时,我得到了这种格式:

[
{'image' : '1.jpg', 'title' : 'Title', 'url' : '', 'age' : 24, 'location' : 'US', 'name' : 'John', 'description' : 'Long Text'},  
{'image' : '1.jpg', 'title' : 'Title', 'url' : '', 'age' : 24, 'location' : 'US', 'name' : 'John', 'description' : 'Long Text'}, 
{'image' : '1.jpg', 'title' : 'Title', 'url' : '', 'age' : 24, 'location' : 'US', 'name' : 'John', 'description' : 'Long Text'}
]

注意包裹变量名的引号。 这使代码无法正常工作。

第一个是 JavaScript数组文字,其中包含object 文字 不是JSON

第二个也是包含对象的数组文字。 更接近JSON ,但不是 100% 有效,因为 JSON 要求所有字符串都用双引号引起来。 例如,这是有效的 JSON:

[{"image": "1.jpg", "title": "Title" }]

如果您不确定您是否正在查看有效的 JSON,您可以随时通过JSONLint运行它并亲自查看。

插件似乎不需要 JSON - 看起来更像某种字典。

有效的 JSON 看起来类似于: {"name":"John", "age":50}

您可能需要构建一个自定义帮助方法来为您的插件正确格式化数据,如果您提供更多源代码可以帮助您:)

我将把这是另一个答案,这样更容易阅读......

在这种情况下,您不想生成 JSON,插件需要一个文字数组,正如 Matt Ball 所说。

基本代码格式将与此类似(将是半 .NET 抱歉......):

public Array GenerateData()
{
// Generate dynamic data here and return as a list / array
}

// Get the data
Array dynamicData = GenerateData();

// Create the template
string template = "[";

// For each item in list, add to the template
foreach (item in dynamicData)
{
    template += "{ image : '" + item[0] + "', title : '" + item[1] + "', url : '" + item[2] + "', age : " + item[3] + ", location : '" + item[4] + "', name : '" + item[5] + "', description : '" + item[6] + "' },"
}

// Add closing brack - may need to trim off last comma also?
string template = "]";

然后将模板字符串嵌入到您的插件初始化中。

暂无
暂无

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

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