[英]How to print json console.log data in browser for use with api
[英]How to print JSON data in console.log?
我无法从 javascript 访问 JSON 数据。 请帮助我如何从 javascript 中的 JSON 数据访问数据。
我有一个 JSON 数据,如
{"success":true,"input_data":{"quantity-row_122":"1","price-row_122":" 35.1 "}}
我试过 console.log(data) 但记录打印对象对象
success:function(data){
console.log(data);
}
如何打印 console.log 特定数据? 我需要打印
quantity-row_122 = 1
price-row_122 = 35.1
console.log(JSON.stringify(data))
会做你需要的。 我假设您正在根据您的代码使用 jQuery。
如果您想要这两个特定值,您可以访问它们并将它们传递给log
。
console.log(data.input_data['quantity-row_122']);
console.log(data.input_data['price-row_122']);
我在 console.log 中使用了 '%j' 选项来打印 JSON 对象
console.log("%j", jsonObj);
{"success":true,"input_data":{"quantity-row_122":"1","price-row_122":" 35.1 "}}
console.dir()
会做你需要的。 它将为您提供数据的层次结构。
success:function(data){
console.dir(data);
}
像这样
> Object
> input_data: Object
price-row_122: " 35.1 "
quantity-row_122: "1"
success: true
我认为您不需要console.log(JSON.stringify(data))
。
要获取数据,您可以在没有stringify
情况下执行此操作:
console.log(data.success); // true
console.log(data.input_data['quantity-row_122']) // "1"
console.log(data.input_data['price-row_122']) // " 35.1 "
笔记
input_data
对象的值将是typeof "1"
: String
,但您可以使用 ParseInt 或 ParseFloat 转换为number(Int or Float)
,如下所示:
typeof parseFloat(data.input_data['price-row_122'], 10) // "number"
parseFloat(data.input_data['price-row_122'], 10) // 35.1
要将对象输出到控制台,您必须先对对象进行字符串化:
success:function(data){
console.log(JSON.stringify(data));
}
如果您只想打印对象,则
console.log(JSON.stringify(data)); //this will convert json to string;
如果要访问对象中字段的值,请使用
console.log(data.input_data);
您还可以使用util
库:
const util = require("util")
> myObject = {1:2, 3:{5:{6:{7:8}}}}
{ '1': 2, '3': { '5': { '6': [Object] } } }
> util.inspect(myObject, {showHidden: true, depth: null})
"{\n '1': 2,\n '3': { '5': { '6': { '7': 8 } } }\n}"
> JSON.stringify(myObject)
'{"1":2,"3":{"5":{"6":{"7":8}}}}'
我通常这样做:
console.log(JSON.stringify(data, undefined, 4));
这是一篇旧帖子,但我要补充一下,因为(正如 Narem 简要提到的) console.log
formatters提供了一些类似 printf 的功能。 在这个问题的情况下,您可以从数据的字符串、数字或 json 格式化程序中受益。
例子:
console.log("Quantity %s, Price: %d", data.quantity-row_122, data.price-row_122);
console.log("Quantity and Price Data %j", data);
目的
input_data: 对象 price-row_122: " 35.1 " 数量-row_122: "1" 成功:true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.