0
<script>
    $( document ).ready(function() {
    jQuery.get('url', function(msg){
        entirePage = JSON.stringify(msg);

        text=(JSON.parse(entirePage));
         console.log(text.productid);
       console.log(text['productname']);


    });
    });
</script>

the result is like the following:

enter image description here

but if i try this code:

 $( document ).ready(function() {
    jQuery.get('url', function(msg){
        entirePage = JSON.stringify(msg);
        text=(JSON.parse(entirePage));
         console.log(text);
    });
    });

I have the following result: enter image description here

8
  • 1
    How do you create json. Commented Mar 12, 2020 at 8:57
  • 1
    i used php code: $myObj->productid = $all_product->getproductid(); $myObj->productname = $all_product->getproductname(); $myObj->detial = $all_product->getdetail(); $myObj->image = $all_product->getimageurl(); $myJSON=json_encode($myObj,JSON_UNESCAPED_UNICODE); echo $myJSON; Commented Mar 12, 2020 at 8:58
  • 1
    Why are you serializing then deserializing the input ? You are doing unnecessary operations Commented Mar 12, 2020 at 9:03
  • 2
    Use the Network tab and check the full response. Make sure there's nothing before or after the JSON. Sometimes there are error messages or HTML. Commented Mar 12, 2020 at 9:07
  • 1
    Network tabs is fine, and I have everything there, but I need to get some html tag inside the json, because I create json from mysql database. Commented Mar 12, 2020 at 9:14

2 Answers 2

2
const myArrStr = JSON.parse(msg);
    console.log(myArrStr[0].productid);

that is it, but make sure you do not have extra things when you create your json.

Sign up to request clarification or add additional context in comments.

Comments

2

Check whether the msg is of type string or object using type of operator before parsing.

I'm not sure why you're stringifying and parsing the same msg object and trying to get some of the properties from it.

If you're just interested in just getting the properties of the returned object. Check the type and proceed..

jQuery.get('url', function(msg) {
    if (typeof msg === 'string') {
        msg = JSON.parse(msg); // you can write a try-block-catch in case if its not a valid JSON
    }

    // additionally check for typeof msg === 'object'
    let productId = msg.productid; // you can add extra check using text.hasOwnProperty('productid'); if not sure
    let productName = msg.productname;
    // ...
});

1 Comment

thank you my problem solved by the previous answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.