简体   繁体   中英

Json response. Retrieve specific values with javascript or php

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

Example of JSON 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]
        }-
    -
    }
} 

 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] }- - } 

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:

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.

To be a valid JSON you need keys to be strings ( "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

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.

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

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

  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> 

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

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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