0

Hii ha ve written this question because i have a json converted to a string with a function of php called json_encode()

Something like this:

{ "data":"2","state":"false"}

when the original json that im trying to encode is like this:

{ "data":2,"state":false}

(Please note that the type of the variables are different, in the original i have an int number called data and boolean called state, but when i use json_encode() every variable goes to a string..)

The problem is when i try to json.PARSE() the value from the json encode of php in angular i don´t get the correct value, every variable is a string...

For example, isntead of getting the boolean state of the variable, i get "false" or "true", and this is a problem...

There is a way to parse this avoiding this problem? basically my problem is when i parse the json in my angular project i dont get the correct type of variable..

Thanks!

9
  • Proper JSON would be: "{\"data\":2,\"state\":false}"; JSON does not handle single-quoted strings. Commented Oct 28, 2021 at 16:14
  • What is the exact code you used to encode the JSON ? Commented Oct 28, 2021 at 16:21
  • Could you clarify your question? Assuming you mean: input: { "data": 2, "state": false} desired output: { "data": "2", "state": "false" } Commented Oct 28, 2021 at 16:24
  • @Hollyol is exactly like that, but when i json.parse in angular i dont get the real values, i get just a string, instead of getting false as a boolean, i get "false" as a string. Commented Oct 28, 2021 at 16:25
  • 1
    Can you try to pass the object to PHP as a string using JSON.stringify() from javascript ? I think it would do the trick Commented Oct 28, 2021 at 16:34

1 Answer 1

0

You can use JSON.parse on an individual value to convert it into the desired type:

const oldValue = JSON.parse('{"data":"2","state":"false"}')

const result = {}

Object.keys(oldValue).forEach(key => {
  result[key] = JSON.parse(oldValue[key]);
});

Here's the other way around:

const oldValue = JSON.parse('{"data": 2,"state": false}');

const result = {}

Object.keys(oldValue).forEach(key => {
  result[key] = oldValue[key].toString();
});

Note: These examples assume flat objects. You'd need to recurse through the object's tree if some of the values are objects, for example {a: {b: "c"}}.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.