Get element from json array javascript

Posted in :

之前大多都做後端, 大多數 json 的處理都是在後端做到, 最近研究如何在 javascript 裡處理 json.

讀取 json 滿簡單的, 一下子就搞定. string to json;
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);

console.log(obj.count);
// Expected output: 42

console.log(obj.result);
// Expected output: true

json object to string:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

console.log(JSON.stringify({ x: 5, y: 6 }));
// Expected output: "{"x":5,"y":6}"

console.log(JSON.stringify([new Number(3), new String('false'), new Boolean(false)]));
// Expected output: "[3,"false",false]"

console.log(JSON.stringify({ x: [10, undefined, function(){}, Symbol('')] }));
// Expected output: "{"x":[10,null,null,null]}"

console.log(JSON.stringify(new Date(2006, 0, 2, 15, 4, 5)));
// Expected output: ""2006-01-02T15:04:05.000Z""

比較麻煩的是換行符號的跳脫, 直接使用 \n 會出錯.

How do I handle newlines in JSON?
https://stackoverflow.com/questions/42068/how-do-i-handle-newlines-in-json

比較簡單的做法, 是\n 變成 \\n

var data = '{"count" : 1, "stack" : "sometext\\n\\n"}';

You need to escape the \ in your string (turning it into a double-\), otherwise it will become a newline in the JSON source, not the JSON data.

function jsonEscape(str)  {
    return str.replace(/\n/g, "\\\\n").replace(/\r/g, "\\\\r").replace(/\t/g, "\\\\t");
}

var data = '{"count" : 1, "stack" : "sometext\n\n"}';
var dataObj = JSON.parse(jsonEscape(data));

另一個比較特別的問題是.

Get element from json array javascript
https://stackoverflow.com/questions/55333968/get-element-from-json-array-javascript

JSON Array Literals
https://www.w3schools.com/js/js_json_arrays.asp

由於 python 用久了, 下面的例子會以為取出的是每一個項目, 但是在 javascript 世界, 其實是取出 array index 類似取出 key ,

Looping Through an Array

You can access array values by using a for in loop:

Example

for (let i in myObj.cars) {
  x += myObj.cars[i];
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *