Json回应。使用javascript或php检索特定值

时间:2022-10-14 16:56:18

I have a API working in shopify and when I use the url of specific task, it gives back a response in JSON. The browser translate it in RAW. However, my question is how can I retrieve specific value from the JSON response? I want just the section "properties" to extract only, with a javascript or php script. The code below is not a file.json, it is a response from the server when I call a specific url. mysite.myshopify.com/admin/orders.json?fields=line_items

我有一个在shopify中工作的API,当我使用特定任务的url时,它会在JSON中返回一个响应。浏览器将其翻译为RAW。但是,我的问题是如何从JSON响应中检索特定值?我想只使用javascript或php脚本提取“属性”部分。下面的代码不是file.json,它是我调用特定URL时服务器的响应。 mysite.myshopify.com/admin/orders.json?fields=line_items

Example of JSON response:

JSON响应示例:

{
    orders: [50]
    0:  {
        name: "#1347"
        line_items: [1]
        0:  {
            fulfillment_service: "manual"
            fulfillment_status: null
            gift_card: false
            grams: 0
            id: 966685828
            price: "45.00"
            product_id: 455951420
            quantity: 1
            requires_shipping: true
            sku: ""
            taxable: true
            title: "Athletic Style Auto renew (ships every 1 Months)"
            variant_id: 1292559264
            variant_title: ""
            vendor: null
            name: "Athletic Style Auto renew (ships every 1 Months)"
            variant_inventory_management: null
            properties: [9]
            0:  {
                name: "Glove Size"
                value: "M"
            }-
            1:  {
                name: "Hat Size"
                value: "L/XL"
            }-
            2:  {
                name: "Pant Size"
                value: "30x30"
            }-
            3:  {
                name: "Right or Left Handed?"
                value: "Right"
            }-
            4:  {
                name: "Shirt Size"
                value: "M"
            }-
            5:  {
                name: "Shoe Size"
                value: "9"
            }-
            6:  {
                name: "shipping_interval_frequency"
                value: "1"
            }-
            7:  {
                name: "shipping_interval_unit_type"
                value: "Months"
            }-
            8:  {
                name: "subscription_id"
                value: "1522"
            }-
            -
            product_exists: true
            fulfillable_quantity: 1
            total_discount: "0.00"
            tax_lines: [0]
        }-
    -
    }
} 

1:  {
line_items: [1]
0:  {
fulfillment_service: "manual"
fulfillment_status: null
gift_card: false
grams: 0
id: 978288644
price: "45.00"
product_id: 449447992
quantity: 1
requires_shipping: true
sku: ""
taxable: true
title: "Loud and Wild Style Auto renew (ships every 1 Months)"
variant_id: 1253803928
variant_title: ""
vendor: null
name: "Loud and Wild Style Auto renew (ships every 1 Months)"
variant_inventory_management: null
properties: [9]
0:  {
name: "Glove Size"
value: "XL"
}-
1:  {
name: "Hat Size"
value: "L/XL"
}-
2:  {
name: "Pant Size"
value: "44x30"
}-
3:  {
name: "Right or Left Handed?"
value: "Left"
}-
4:  {
name: "Shirt Size"
value: "XXL"
}-
5:  {
name: "Shoe Size"
value: "10.5"
}-
6:  {
name: "shipping_interval_frequency"
value: "1"
}-
7:  {
name: "shipping_interval_unit_type"
value: "Months"
}-
8:  {
name: "subscription_id"
value: "1523"
}-
-
product_exists: true
fulfillable_quantity: 1
total_discount: "0.00"
tax_lines: [0]
}-
-
}-
2:  {...}-
3:  {
line_items: [1]
0:  {
fulfillment_service: "manual"
fulfillment_status: null
gift_card: false
grams: 0
id: 974181252
price: "45.00"
product_id: 455951420
quantity: 1
requires_shipping: true
sku: ""
taxable: true
title: "Athletic Style Auto renew (ships every 1 Months)"
variant_id: 1292559264
variant_title: ""
vendor: null
name: "Athletic Style Auto renew (ships every 1 Months)"
variant_inventory_management: null
properties: [9]
0:  {
name: "Glove Size"
value: "XL"
}-
1:  {
name: "Hat Size"
value: "L/XL"
}-
2:  {
name: "Pant Size"
value: "42x30"
}-
3:  {
name: "Right or Left Handed?"
value: "Right"
}-
4:  {
name: "Shirt Size"
value: "XXL"
}-
5:  {
name: "Shoe Size"
value: "12"
}-
6:  {
name: "shipping_interval_frequency"
value: "1"
}-
7:  {
name: "shipping_interval_unit_type"
value: "Months"
}-
8:  {
name: "subscription_id"
value: "1522"
}-
-
product_exists: true
fulfillable_quantity: 1
total_discount: "0.00"
tax_lines: [0]
}-
-
}

3 个解决方案

#1


It sounds like you're looking for json_decode if you want to use PHP

如果你想使用PHP,听起来你正在寻找json_decode

PHP

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));

?>

http://php.net/manual/en/function.json-decode.php

In your scenario:

在您的方案中:

$response = //your api response
$php_obj = json_decode($response);

//Print a specific order and specific items properties
var_dump($php_obj->orders[0]->line_items[0]->properties);

//Print the properties for each item in each order 
//(prefixed with the index of the order number and item number)
foreach ($php_obj->orders as $order_index => $order) {
   foreach ($order->line_items as $item_index => $item) {
     echo "order: {$order_index} item: {$item_index}";
     var_dump($item->properties);
   }
}

If you want to use JS

如果你想使用JS

PHP/JS

<script>
  var response = "<?php echo $response; /*again your api response*/ ?>";
  var obj = JSON.parse(response);
  console.log(obj.orders[0].line_items[0].properties)
</script>

#2


As people says in the comments, your response is not valid JSON. The closest valid object to the one you posted will be formatted as this:

正如人们在评论中所说,您的回答不是有效的JSON。与您发布的对象最接近的有效对象将格式化为:

var response = {
orders: [50],
0:{
    name: "#1347",
    line_items: [1],
    0:{
        fulfillment_service: "manual",
        fulfillment_status: null,
        gift_card: false,
        grams: 0,
        id: 966685828,
        price: "45.00",
        product_id: 455951420,
        quantity: 1,
        requires_shipping: true,
        sku: "",
        taxable: true,
        title: "Athletic Style Auto renew (ships every 1 Months)",
        variant_id: 1292559264,
        variant_title: "",
        vendor: null,
        name: "Athletic Style Auto renew (ships every 1 Months)",
        variant_inventory_management: null,
        properties: [9],
        0:  {
            name: "Glove Size",
            value: "M"
        },
        1:  {
            name: "Hat Size",
            value: "L/XL"
        },
        2:  {
            name: "Pant Size",
            value: "30x30"
        },
        3:  {
            name: "Right or Left Handed?",
            value: "Right"
        },
        4:  {
            name: "Shirt Size",
            value: "M"
        },
        5:  {
            name: "Shoe Size",
            value: "9"
        },
        6:  {
            name: "shipping_interval_frequency",
            value: "1"
        },
        7:  {
            name: "shipping_interval_unit_type",
            value: "Months"
        },
        8:  {
            name: "subscription_id",
            value: "1522"
        },
        product_exists: true,
        fulfillable_quantity: 1,
        total_discount: "0.00",
        tax_lines: [0]
      }
   }
};

This is valid javascript object but not JSON object.

这是有效的javascript对象,但不是JSON对象。

To be a valid JSON you need keys to be strings ( "key":value )

要成为有效的JSON,您需要将键作为字符串(“key”:value)

{
"orders": [50],
"0":{
    "name": "#1347",
    "line_items": [1],
    "0":{
        "fulfillment_service": "manual",
        "fulfillment_status": null,
        "gift_card": false,
        "grams": 0,
        "id": 966685828,
        "price": "45.00",
        "product_id": 455951420,
        "quantity": 1,
        "requires_shipping": true,
        "sku": "",
        "taxable": true,
        "title": "Athletic Style Auto renew (ships every 1 Months)",
        "variant_id": 1292559264,
        "variant_title": "",
        "vendor": null,
        "name": "Athletic Style Auto renew (ships every 1 Months)",
        "variant_inventory_management": null,
        "properties": [9],
        "0":  {
            "name": "Glove Size",
            "value": "M"
        },
        "1":  {
            "name": "Hat Size",
            "value": "L/XL"
        },
        "2":  {
            "name": "Pant Size",
            "value": "30x30"
        },
        "3":  {
            "name": "Right or Left Handed?",
            "value": "Right"
        },
        "4":  {
            "name": "Shirt Size",
            "value": "M"
        },
        "5":  {
            "name": "Shoe Size",
            "value": "9"
        },
        "6":  {
            "name": "shipping_interval_frequency",
            "value": "1"
        },
        "7":  {
            "name": "shipping_interval_unit_type",
            "value": "Months"
        },
        "8":  {
            "name": "subscription_id",
            "value": "1522"
        },
        "product_exists": true,
        "fulfillable_quantity": 1,
        "total_discount": "0.00",
        "tax_lines": [0]
      }
   }
}

If you want to extract the properties, once you you have a reference of your object you can access it with Javascript as

如果要提取属性,一旦有了对象的引用,就可以使用Javascript作为对象进行访问

var myProperties = response["0"]["0"]["properties"];

In PHP after you perform a JSON parse on your response, you can access them as a nested associative array.

在PHP上对响应执行JSON解析后,可以将它们作为嵌套关联数组进行访问。

 $myResponse = json_decode($response);
 $myProperties = $response['0']['0']['properties'];

#3


The data format is incorrect. It is missing commas and brackets. Compare with the working code below to find the dependencies.

数据格式不正确。它缺少逗号和括号。与下面的工作代码比较,找到依赖项。

Once the data is in correct format it is just a matter of using dot and bracket notation to access. Play with the code below to understand better.

一旦数据格式正确,只需使用点和括号表示法即可访问。使用下面的代码来更好地理解。

Reference: Mozilla - Working with Objects

参考:Mozilla - 使用对象

  data['0']['0'].title;

Run code snippet to test:

运行代码片段进行测试:

<html>
<body>
  
  Value:
  <div id="value" style="font-family:monospace;font-size:16px;"></div>
  <p>
  JSON:
  <textarea id="json" style="background-color:aliceblue;padding:0.5em;border:1px black solid;width:100%; height:40em;"></textarea>

  <script type="text/javascript">


    var data = {
      orders: [50],
      0:
      {
        name: "#1347",
        line_items: [1],
        0:
        {
          fulfillment_service: "manual",
          fulfillment_status: null,
          gift_card: false,
          grams: 0,
          id: 966685828,
          price: "45.00",
          product_id: 455951420,
          quantity: 1,
          requires_shipping: true,
          sku: "",
          taxable: true,
          title: "Athletic Style Auto renew (ships every 1 Months)",
          variant_id: 1292559264,
          variant_title: "",
          vendor: null,
          name: "Athletic Style Auto renew (ships every 1 Months)",
          variant_inventory_management: null,
          properties: [9],
          0:
          {
            name: "Glove Size",
            value: "M"
          },
          1:
          {
            name: "Hat Size",
            value: "L/XL"
          },
          2:
          {
            name: "Pant Size",
            value: "30x30"
          }
        }
      }
    };
    
    
    document.getElementById('value').innerHTML = data['0']['0'].title;
    
    document.getElementById('json').value = 'json:\n' + JSON.stringify(data, null, '  ');
    
  </script>
</body>
</html>

#1


It sounds like you're looking for json_decode if you want to use PHP

如果你想使用PHP,听起来你正在寻找json_decode

PHP

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));

?>

http://php.net/manual/en/function.json-decode.php

In your scenario:

在您的方案中:

$response = //your api response
$php_obj = json_decode($response);

//Print a specific order and specific items properties
var_dump($php_obj->orders[0]->line_items[0]->properties);

//Print the properties for each item in each order 
//(prefixed with the index of the order number and item number)
foreach ($php_obj->orders as $order_index => $order) {
   foreach ($order->line_items as $item_index => $item) {
     echo "order: {$order_index} item: {$item_index}";
     var_dump($item->properties);
   }
}

If you want to use JS

如果你想使用JS

PHP/JS

<script>
  var response = "<?php echo $response; /*again your api response*/ ?>";
  var obj = JSON.parse(response);
  console.log(obj.orders[0].line_items[0].properties)
</script>

#2


As people says in the comments, your response is not valid JSON. The closest valid object to the one you posted will be formatted as this:

正如人们在评论中所说,您的回答不是有效的JSON。与您发布的对象最接近的有效对象将格式化为:

var response = {
orders: [50],
0:{
    name: "#1347",
    line_items: [1],
    0:{
        fulfillment_service: "manual",
        fulfillment_status: null,
        gift_card: false,
        grams: 0,
        id: 966685828,
        price: "45.00",
        product_id: 455951420,
        quantity: 1,
        requires_shipping: true,
        sku: "",
        taxable: true,
        title: "Athletic Style Auto renew (ships every 1 Months)",
        variant_id: 1292559264,
        variant_title: "",
        vendor: null,
        name: "Athletic Style Auto renew (ships every 1 Months)",
        variant_inventory_management: null,
        properties: [9],
        0:  {
            name: "Glove Size",
            value: "M"
        },
        1:  {
            name: "Hat Size",
            value: "L/XL"
        },
        2:  {
            name: "Pant Size",
            value: "30x30"
        },
        3:  {
            name: "Right or Left Handed?",
            value: "Right"
        },
        4:  {
            name: "Shirt Size",
            value: "M"
        },
        5:  {
            name: "Shoe Size",
            value: "9"
        },
        6:  {
            name: "shipping_interval_frequency",
            value: "1"
        },
        7:  {
            name: "shipping_interval_unit_type",
            value: "Months"
        },
        8:  {
            name: "subscription_id",
            value: "1522"
        },
        product_exists: true,
        fulfillable_quantity: 1,
        total_discount: "0.00",
        tax_lines: [0]
      }
   }
};

This is valid javascript object but not JSON object.

这是有效的javascript对象,但不是JSON对象。

To be a valid JSON you need keys to be strings ( "key":value )

要成为有效的JSON,您需要将键作为字符串(“key”:value)

{
"orders": [50],
"0":{
    "name": "#1347",
    "line_items": [1],
    "0":{
        "fulfillment_service": "manual",
        "fulfillment_status": null,
        "gift_card": false,
        "grams": 0,
        "id": 966685828,
        "price": "45.00",
        "product_id": 455951420,
        "quantity": 1,
        "requires_shipping": true,
        "sku": "",
        "taxable": true,
        "title": "Athletic Style Auto renew (ships every 1 Months)",
        "variant_id": 1292559264,
        "variant_title": "",
        "vendor": null,
        "name": "Athletic Style Auto renew (ships every 1 Months)",
        "variant_inventory_management": null,
        "properties": [9],
        "0":  {
            "name": "Glove Size",
            "value": "M"
        },
        "1":  {
            "name": "Hat Size",
            "value": "L/XL"
        },
        "2":  {
            "name": "Pant Size",
            "value": "30x30"
        },
        "3":  {
            "name": "Right or Left Handed?",
            "value": "Right"
        },
        "4":  {
            "name": "Shirt Size",
            "value": "M"
        },
        "5":  {
            "name": "Shoe Size",
            "value": "9"
        },
        "6":  {
            "name": "shipping_interval_frequency",
            "value": "1"
        },
        "7":  {
            "name": "shipping_interval_unit_type",
            "value": "Months"
        },
        "8":  {
            "name": "subscription_id",
            "value": "1522"
        },
        "product_exists": true,
        "fulfillable_quantity": 1,
        "total_discount": "0.00",
        "tax_lines": [0]
      }
   }
}

If you want to extract the properties, once you you have a reference of your object you can access it with Javascript as

如果要提取属性,一旦有了对象的引用,就可以使用Javascript作为对象进行访问

var myProperties = response["0"]["0"]["properties"];

In PHP after you perform a JSON parse on your response, you can access them as a nested associative array.

在PHP上对响应执行JSON解析后,可以将它们作为嵌套关联数组进行访问。

 $myResponse = json_decode($response);
 $myProperties = $response['0']['0']['properties'];

#3


The data format is incorrect. It is missing commas and brackets. Compare with the working code below to find the dependencies.

数据格式不正确。它缺少逗号和括号。与下面的工作代码比较,找到依赖项。

Once the data is in correct format it is just a matter of using dot and bracket notation to access. Play with the code below to understand better.

一旦数据格式正确,只需使用点和括号表示法即可访问。使用下面的代码来更好地理解。

Reference: Mozilla - Working with Objects

参考:Mozilla - 使用对象

  data['0']['0'].title;

Run code snippet to test:

运行代码片段进行测试:

<html>
<body>
  
  Value:
  <div id="value" style="font-family:monospace;font-size:16px;"></div>
  <p>
  JSON:
  <textarea id="json" style="background-color:aliceblue;padding:0.5em;border:1px black solid;width:100%; height:40em;"></textarea>

  <script type="text/javascript">


    var data = {
      orders: [50],
      0:
      {
        name: "#1347",
        line_items: [1],
        0:
        {
          fulfillment_service: "manual",
          fulfillment_status: null,
          gift_card: false,
          grams: 0,
          id: 966685828,
          price: "45.00",
          product_id: 455951420,
          quantity: 1,
          requires_shipping: true,
          sku: "",
          taxable: true,
          title: "Athletic Style Auto renew (ships every 1 Months)",
          variant_id: 1292559264,
          variant_title: "",
          vendor: null,
          name: "Athletic Style Auto renew (ships every 1 Months)",
          variant_inventory_management: null,
          properties: [9],
          0:
          {
            name: "Glove Size",
            value: "M"
          },
          1:
          {
            name: "Hat Size",
            value: "L/XL"
          },
          2:
          {
            name: "Pant Size",
            value: "30x30"
          }
        }
      }
    };
    
    
    document.getElementById('value').innerHTML = data['0']['0'].title;
    
    document.getElementById('json').value = 'json:\n' + JSON.stringify(data, null, '  ');
    
  </script>
</body>
</html>