json字符串转json对象
时间: 2023-09-20 08:09:30 浏览: 111
在大多数编程语言中,可以使用内置的JSON解析器将JSON字符串转换为JSON对象。以下是一些示例:
在JavaScript中:
```javascript
const jsonStr = '{"name":"John","age":30,"city":"New York"}';
const jsonObj = JSON.parse(jsonStr);
console.log(jsonObj); // 输出 { name: 'John', age: 30, city: 'New York' }
```
在Python中:
```python
import json
json_str = '{"name": "John", "age": 30, "city": "New York"}'
json_obj = json.loads(json_str)
print(json_obj) # 输出 {'name': 'John', 'age': 30, 'city': 'New York'}
```
在Java中:
```java
import com.fasterxml.jackson.databind.ObjectMapper;
String jsonStr = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonStr);
System.out.println(jsonNode); // 输出 {"name":"John","age":30,"city":"New York"}
```
在PHP中:
```php
$jsonStr = '{"name":"John","age":30,"city":"New York"}';
$jsonObj = json_decode($jsonStr);
print_r($jsonObj); // 输出 stdClass Object ( [name] => John [age] => 30 [city] => New York )
```
在C#中:
```csharp
using System.Text.Json;
string jsonStr = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
JsonDocument jsonDoc = JsonDocument.Parse(jsonStr);
Console.WriteLine(jsonDoc.RootElement); // 输出 {"name":"John","age":30,"city":"New York"}
```
阅读全文